ruby-on-railsmodelpaperclip

Paperclip use params in :url option


I have two models: photos and properties. A property has_many photos. When uploading a photo via paperclip I want the directory structure to be something like properties/the_property_id/:id.:style (of course, the second :id here would be the image id since thats what model were in).

A photo is added and edited via the properties model (accepts_nested_attributes_for). So, while viewing the property edit page I need a way of passing the property id (params[:id]) to the photos model so paperclip can use something like :url => properties/params[:id]/:style/:id.:extension. (properties/6/small/2.jpg)

Looking for advice on the best way to do this... How would you accomplish this task?


Solution

  • You need to use Paperclip interpolations(see https://github.com/thoughtbot/paperclip/wiki/Interpolations for details). Then you can have something like this:

    Paperclip.interpolates :param_value do |attachment, style|
      attachment.instance.property.params[attachment.instance.id]
    end
    

    And use it in your model in such way:

    :url => properties/:param_value/:style/:id.:extension