I'm interested in getting the nested 'name' parameter of a params hash. Calling something like
params[:subject][:name]
throws an error when params[:subject] is empty. To avoid this error I usually write something like this:
if params[:subject] && params[:subject][:name]
Is there a cleaner way to implement this?
e.g.
You can use
#try
, but I don't think it's much better:Or use
#fetch
with default parameter:Or you can set
#default=
to new empty hash, but then don't try to modify values returned from this:It also breaks all simple tests for existence, so you can't write:
because it will return empty hash, now you have to add
#present?
call to every test.Also this always returns hash when there is no value for key, even when you expect string.
But from what I see, you try to extract nested parameter, instead of assigning it to model and there placing your logic. If you have
Subject
model, then simply assigning:shuld extract all your parameters user filled in form. Then you try to save them, to see if user passed valid values.
If you're worrying about accessing fields which user should not set, then add
attr_accessible
whitelist for fields whoich should be allowed to set with mass assignment (as in my example, of with@subject.attributes = params[:subject]
for update)params[:subject].try(:[], :name)
is the cleanest wayI used:
gives:
Ruby 2.3.0 makes this very easy to do with #dig
Or, add
[]
to it.