Posted almost 12 years ago. Visible to the public.

Take care when merging with params

Be careful when using params.merge as params is a HashWithIndifferentAccess Archive .


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 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.)

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Arne Hartherz
Last edit:
almost 12 years ago
exception, error
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more