简体   繁体   English

Rails的生存时间可变

[英]Rails life time of params variable

In the standard "index" method of controller I set some value in the params hash in order to use it in the view if it's not initialized yet in other case do nothing. 在控制器的标准“索引”方法中,我在params哈希中设置了一些值,以便在尚未初始化的情况下在视图中使用它,否则在其他情况下什么也不做。

def index
  params[:my_value] ||= {}
end

when I use include? 当我使用包括? method on the params[:my_value] in the view, there's an error evaluating nil.include? 视图中的params [:my_value]上的方法,评估nil.include时出错。

Why there's such error if params[:my_value] cannot be nil. 如果params [:my_value]不能为nil,为什么会有这样的错误。 If it's nil, its value should be initialized with {}, that's what ||= operator does. 如果为nil,则应使用{}初始化其值,这就是|| =运算符的作用。 What can be the problem here? 这可能是什么问题?

The solution was in the merge method. 解决方案是在合并方法中。 It turned out that 事实证明

a = b.merge(a) 

and

a.merge(b) {|key, v1, v2| v1 }

do different things and in the first case(which was wrong) nil appears somewhere. 做不同的事情,在第一种情况(这是错误的)中,nil出现在某处。 I haven't figured out yet why is it so because merge method always return a hash and when I replaced the first variant with the second everything was ok. 我还没有弄清楚为什么会这样,因为merge方法总是返回一个哈希,当我用第二个替换第一个变量时,一切正常。 So I don't see any problem... 所以我没看到任何问题...

rails parameters exists upto request flow completes Rails参数存在直至请求流完成

You can access params inside view page going to be rendered but params will not be available if you are doing re-direction to another page inside controller action as it interrupts request flow. 您可以访问要呈现的视图页面内部的params但是如果您正在重定向到控制器动作中的另一个页面,则参数将不可用,因为它会中断请求流。

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

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