Tuesday, February 19, 2013

Paperclip order of params

In my website I'm using Paperclip to take care of the attached files.

I have a model "image" who has many "collections".
A "collection" belongs to a "resolution".

I'm displaying the form of an image with a list of available resolutions.

In the model Collection:
has_attached_file :picture,
    :url => "...",
    :path => "...",
    :styles => { :custom => Proc.new { |col| "#{col.resolution.width}x#{col.resolution.height}" }}
   }}

Problem
When an image is updated, the Proc is executed and I have a "nil" exception.
I'm wondering why "resolution" is nil because the params contain a resolution_id.

Solution
In fact, it depends of the order you pass the parameters.

At first, the view was like this :
= f.file_field :picture
= f.hidden_field :resolution_id

But I should do like this:
= f.hidden_field :resolution_id
= f.file_field :picture


The "resolution_id" should be first !
By doing so, Rais is creating the relation between "resolution" and "collection" first, and then he is applying the style.

So, sometimes the order of the params is important!

And that's it!

Edit
Too bad for me, in fact the order is not sure... It is working on my development environment, but not in my production environment...

No comments: