在 Rails 中分配/替换 params 哈希 [英] assign/replace params hash in rails

查看:31
本文介绍了在 Rails 中分配/替换 params 哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 rails 控制器操作中有以下代码序列.在 IF 之前,params 包含请求参数,正如预期的那样.之后,params 为零.谁能解释一下这里发生了什么?

如果为假参数 = {:user =>{:name =>"用户", :comment =>'评论'}}结尾

谢谢.

解决方案

包含请求参数的 params 实际上是一个方法调用,它返回一个包含参数的哈希值.您的 params = 行正在分配给名为 params 的局部变量.

if false 块之后,Ruby 已经看到了局部 params 变量,所以当你稍后在方法中引用 params 时,局部变量优先于调用同名方法.然而,因为你的 params = 赋值在一个 if false 块中,所以局部变量永远不会被赋值,所以局部变量是 nil.>

如果你在赋值之前试图引用一个局部变量,你会得到一个 NameError:

irb(main):001:0>巴兹NameError:main:Object 的未定义局部变量或方法baz"来自 (irb):1

但是,如果对不在代码执行路径中的变量进行赋值,则 Ruby 已创建局部变量,但其值为 nil.

irb(main):007:0>baz = "示例" 如果为假=>零irb(main):008:0>巴兹=>零

参见:赋值 - Ruby 文档中的局部变量和方法.

I have the code sequence below in a rails controller action. Before the IF, params contains the request parameters, as expected. After it, params is nil. Can anyone please explain what is happening here?

if false
    params = {:user => {:name => "user", :comment => 'comment'}}
end

Thank you.

解决方案

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

See: Assignment - Local Variables and Methods in the Ruby docs.

这篇关于在 Rails 中分配/替换 params 哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆