3

In rails 4, I can merge! StrongParams, but since rails 5 (beta1) merge! is not available. Which is the best way to do that in a controller

  params = ActionController::Parameters.new({
             name: 'Francesco',
             age:  22,
             role: 'admin'
         })
         params.merge!(city: "Los Angeles")
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
Olivier
  • 493
  • 2
  • 6
  • 16

4 Answers4

10

As far as I can see from the source code, you have merge not merge!. In other words, it doesn't seem to be possible to modify the hash in place.

The following code will work:

params = ActionController::Parameters.new({
             name: 'Francesco',
             age:  22,
             role: 'admin'
         })
params = params.merge(city: "Los Angeles")
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
2

params.merge!(city: "Los Angeles") works with Rails5.0.1

enter image description here

In Rails 5: ActionController::Parameters Now Returns an Object Instead of a Hash.

so you must use params.permit(:city).to_h to access city.

For more details how ActionController::Parameters works in Rails5?

Ref: http://www.rortuts.com/ruby-on-rails/rails5-actioncontrollerparameters/

Vaibhav
  • 858
  • 10
  • 13
0

Hope this helps to anyone.

def comment_params
  params.require(:comment).permit(:title, :user_id, :color)
end

I want to merge color attribute with my custom color code or name. so to merge color attribute dynamically

Ininitialize params in rails 5 like this,

params = ActionController::Parameters.new(comment_params)
params = params.merge(color: "green")
SSR
  • 6,398
  • 4
  • 34
  • 50
-2
new_params = params.to_h.merge(city: "Los Angeles")
Weston Ganger
  • 6,324
  • 4
  • 41
  • 39