I have set up my models to use a polymorphic Image model. This is working fine, however I am wondering if it is possible to change the :styles setting for each model. Found some
After couple of hours of digging into source code of both, ActiveRecord
and Paperclip
, I think there's a solution involving a bit of monkey-patching hackery.
I haven't thoroughly tested it but seems to work for my humble needs.
Below is my config/initializers/activerecord_associations_patch.rb
:
module ActiveRecord
module Associations
class HasManyAssociation
def build_record(attributes)
if options[:as] && owner
# Unicorns
reflection.build_association({}) do |record|
set_owner_attributes(record)
unless foreign_key_for?(record)
record.public_send "#{options[:as]}=", owner
end
initialize_attributes(record)
record.assign_attributes(attributes)
end
else
# Classic Rails way
reflection.build_association(attributes) do |record|
initialize_attributes(record)
end
end
end
end
end
end
Since reflection
doesn't know our @owner
, it first assigns the attributes
which triggers call to record.#{instance}=
(i.e. Image#file=
), which in turn forwards it to #assign
and performs post_processing
hook, which in the end leads to calling styles
Proc
provided in has_attached_file
without polymorphic imageable
being set. huh…
I rewrote the method to build the record first and assign provided attributes later.
Also, it accounts for record#new_record?
in foreign_key_for?
check.
In this way attributes
are assigned once the record has been properly setup. At least i think so ;)
Cleaner solutions and constructive comments are most welcome :)