[英]How does Rails know the difference between these two identical expressions?
I am using a 4-year old Rails tutorial and I have Rails 4.0.2. 我正在使用一个4岁的Rails教程,我有Rails 4.0.2。 I made a model called "Thing" and a controller called "Things".
我制作了一个名为“Thing”的模型和一个名为“Things”的控制器。 The "Thing" model has one attribute called "data".
“Thing”模型有一个名为“data”的属性。 In my
create
action, I had this line: 在我的
create
动作中,我有这一行:
@thing = Thing.new(params[:thing])
which results in this error: 这会导致此错误:
ActiveModel::ForbiddenAttributesError in ThingsController#create
I found a StackOverflow thread that said I needed to require
my needed parameters, and that worked just fine. 我发现一个StackOverflow的线程说我需要
require
我所需要的参数,并且工作得很好。
Before I looked that up I tried putting the hash from my params directly into the Thing.new()
method and I didn't get an error. 在我查看之前,我尝试将我的参数中的哈希直接放入
Thing.new()
方法中,但我没有收到错误。 I started with this line: 我从这一行开始:
puts params[:thing]
in my create
action, typed "12345" in my text field, hit submit and got this in the console: 在我的
create
操作中,在我的文本字段中键入“12345”,点击提交并在控制台中获取:
{"data"=>"12345"}
So I tried this in the create
action: 所以我在
create
动作中尝试了这个:
@thing = Thing.new({"data" => "12345"})
and I didn't get the error. 我没有得到错误。 I even confirmed they were identical by doing this:
我甚至通过这样做确认他们是完全相同的:
puts params[:thing] == {"data"=>"12345"}
and I get "true" on the console. 我在控制台上得到“真实”。 So,
所以,
Thing.new(params[:thing])
gives me the error, but 给了我错误,但是
Thing.new({"data"=>"12345"})
does not. 才不是。
How can Rails tell the difference between these two arguments when they seem to be identical? 当Rails看起来相同时,Rails如何区分这两个论点?
params[:thing]
is not the same thing as {"data" => "12345"}
, they just have the same value when inspect
is called on them, and params
's class overrides ==
to say it's equal to the hash. params[:thing]
是不一样的东西{"data" => "12345"}
他们只是有当值相同inspect
叫上他们, params
的类重写==
说这等于散列。
Rails 4+ uses Strong Parameters , which is a security feature to make sure you know what you're putting in your models. Rails 4+使用强参数 ,这是一个安全功能,以确保您知道您在模型中的内容。 Basically, Rails wants to you check the validity of the parameters.
基本上,Rails想要检查参数的有效性。 It lets you do
Thing.new({"data" => "12345"})
because you, the developer, are creating the Hash directly, and are more trustworthy than someone on the internet calling your server. 它允许你做
Thing.new({"data" => "12345"})
因为你,开发人员,直接创建哈希,并且比在互联网上呼叫你的服务器的人更可靠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.