Read more

Take care when merging with params

Arne Hartherz
October 22, 2010Software engineer at makandra GmbH

Be careful when using params.merge as params is a HashWithIndifferentAccess Show archive.org snapshot .

Why?

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

Usually this should not be an issue but it turns crazy if you try to include associated models deeper than 1 level:
options = params.merge(:include => { :user => :avatar })
Post.paginate options

When inspecting the merged params you will get something like this:
{ :include=> { "user" => :avatar }, :page => 23 }

Here the :user symbol in the hash of inclusions turned into a "user" string.\
This breaks Rails' loading of associations as it will complain about calling nil.name or nil.macro while it tries to process the association list.

Best practice

Make sure to do it this way:
params.to_hash.symbolize_keys.merge(:include => { :user => :avatar })

(Note that params.to_hash returns a hash with string keys.)

Posted by Arne Hartherz to makandra dev (2010-10-22 16:34)