有一些旧代码,在某些情况下会修改参数。我相信它以前有效(不是 100%)。无论条件是否满足,我们现在都将 params 设置为 nil。
罪魁祸首在条件之内,我执行了params = tmp.dup
.即使条件为假,这也会导致更新操作出错。
我能够通过最少的测试重新创建
( rails 2.3.5)
rails bug;
cd bug;
script/generate scaffold bug name:string;
rake db:create;
rake db:migrate;
编辑应用程序/ Controller /bugs_controller.rb
添加到更新操作的开头
l_p = params.dup
if (false)
params = l_p.dup # NOT REACHED
end
脚本/服务器 WEBrick -p 5001
浏览到 http://localhost:5001/bugs
创建一个新错误
编辑错误
提交
最佳答案
根据 user45147 评论,此问题的正确答案在这里:
assign/replace params hash in rails
复制到这里:
The
params
which contains the request parameters is actually a method call which returns a hash containing the parameters. Yourparams =
line is assigning to a local variable calledparams
.After the
if false
block, Ruby has seen the localparams
variable so when you refer toparams
later in the method the local variable has precedence over calling the method of the same name. However because yourparams =
assignment is within anif false
block the local variable is never assigned a value so the local variable isnil
.If you attempt to refer to a local variable before assigning to it you will get a NameError:
irb(main):001:0> baz NameError: undefined local variable or method `baz' for main:Object from (irb):1
However if there is an assignment to the variable which isn't in the code execution path then Ruby has created the local variable but its value is
nil
.irb(main):007:0> baz = "Example" if false => nil irb(main):008:0> baz => nil
关于ruby-on-rails - 参数变为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3723491/