Killerpixler
Killerpixler

Reputation: 4050

Rails params, params.merge error

In order to keep params filter and filter_type through a ajax form submit, I pass them in as hidden fields in my article form which as a result gives me this params hash:

{"utf8"=>"✓", "_method"=>"patch", "article"=>{"filter"=>"xxx", "filter_type"=>"xxxx", ....actual fields of the model that got updated...}, "commit"=>"Update Article", "controller"=>"articles", "action"=>"update", "id"=>"xxx"}

Which means I can access them through params[:article]["filter"].

When I, in my controller's update method, call params.merge(filter: params[:article]["filter"]) nothing gets appended. When I try params = params.merge(filter: params[:article]["filter"]) I get this error NoMethodError (undefined method '[]' for nil:NilClass):

and here comes the weird part: When I do @foo = params.merge(filter: params[:article]["filter"]) I also don't get anything added until I actually output @foo in the view. As soon as I have the <%= @foo %> in my view, the params get properly merged. Can somebody explain why that is?

Upvotes: 2

Views: 281

Answers (1)

MurifoX
MurifoX

Reputation: 15089

I think it is better for you to not pass them as articles child. Instead of using f.hidden_field :filter you could use hidden_field_tag :filter, so you will receive the params like: { filter: "filter", article: {}}. This way there is no need to merge.

Upvotes: 2

Related Questions