简体   繁体   English

在Rails 5中,是否可以修改控制器中的基础参数? 还是给它一个默认值?

[英]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. 在Rails 5控制器中,您可以调用params并返回请求中参数的哈希值。

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. 但是,如果代码中的其他许多地方期望使用params [:starting_value],则此解决方案可能需要进行一些混乱的更改。

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! 我认为您正在寻找merge! method. 方法。 Docs Here 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. 您需要它来保留更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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