ruby-on-rails - 参数变为 nil

标签 ruby-on-rails controller params

有一些旧代码,在某些情况下会修改参数。我相信它以前有效(不是 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. Your params = line is assigning to a local variable called params.

After the if false block, Ruby has seen the local params variable so when you refer to params later in the method the local variable has precedence over calling the method of the same name. However because your params = assignment is within an if false block the local variable is never assigned a value so the local variable is nil.

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/

相关文章:

javascript - rails 4 : Is it necessary to explicitly enable Sprockets for Asset Pipeline?

c# - 如何使用 MVC 动态构建多个站点

javascript - 从 Rails 中的 Controller 打开弹出窗口

json - Grails 2.4.3,升级参数,要求

unit-testing - Grails单元测试 Controller 设置参数

ruby-on-rails - RSpec请求测试合并了POST JSON参数中数组中的哈希

sql - Rails 3 Sum 两个领域的产品

ruby-on-rails - rails 3.2.6; rake 0.9.2.2;数据库:migrate aborted

mysql - 三、Yii中sql语句中的and条件

ruby-on-rails - Rails sunspot-solr - 带连字符的单词