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")
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")
params.merge!(city: "Los Angeles") works with Rails5.0.1
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/
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")
new_params = params.to_h.merge(city: "Los Angeles")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.