简体   繁体   中英

In Rails 5, is there a way to modify the underlying params in a controller? Or give it a default?

In a Rails 5 controller, you can call params and it returns a hash of the parameters from the request.

But you can't modify the params that way. Because what you're modifying is a copy of the params hash values, not a reference to the underlying params.

params[:starting_value] ||= "abc" # doesn't work for my purposes

What you're supposed to do is store the values elsewhere.

@starting_value = params[:starting_value] || "abc"

But if a bunch of other places in the code expect params[:starting_value], then this solution might require some messy changes.

Is there a way to set the default value of a param in the controller? Or am I going to have to do it the slightly messier way.

I could also accomplish what I want with a redirect, but that isn't ideal either.

I think you're looking for the merge! method. Docs Here

params = params.merge!(:starting_value, 'abc)

It returns the original params with the new one merged in or overwritten. Be aware that merge without an exclamation mark does not modify in place. You need it to keep the changes.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM