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
I am really late to the party here, but I wanted to clarify something about accessing model data for anyone else that happens on to this thread. I just faced this issue while using Paperclip to apply watermarks based on data from the model, and got it working after a lot of investigation.
You said:
After reading a lot on the Paperclip forum I don't believe it's possible to access the instance before it has been saved. You can only see the Paperclip stuff and that's it.
In fact, you can see the model data if it's been set in the object before your attachment is assigned!
Your paperclip processors and whatnot are invoked when the attachment in your model is assigned. If you rely on mass assignment (or not, actually), as soon as the attachment is assigned a value, paperclip does its thing.
Here's how I solved the problem:
In my model with the attachment (Photo), I made all the attributes EXCEPT the attachment attr_accessible
, thereby keeping the attachment from being assigned during mass assignment.
class Photo < ActiveRecord::Base
attr_accessible :attribution, :latitude, :longitude, :activity_id, :seq_no, :approved, :caption
has_attached_file :picture, ...
...
end
In my controller's create method (for example) I pulled out the picture
from the params
, and then created the object. (It's probably not necessary to remove the picture from params
, since the attr_accessible
statement should prevent picture
from being assgined, but it doesn't hurt). Then I assign the picture
attribute, after all the other attributes of the photo object have been setup.
def create
picture = params[:photo].delete(:picture)
@photo = Photo.new(params[:photo])
@photo.picture = picture
@photo.save
...
end
In my case, one of the styles for picture calls for applying a watermark, which is the text string held in the attribution
attribute. Before I made these code changes, the attribution string was never applied, and in the watermark code, attachment.instance.attribution
was always nil
. The changes summarized here made the entire model available inside the paperclip processors. The key is to assign your attachment attribute last.
Hope this helps someone.