问题描述
Rails 4 文档中所有强参数的例子都使用
All the examples of strong parameters in Rails 4 docs use
params.require(:person).permit(:name, :age)
有人可以解构并解释这里的 require
和 permit
发生了什么吗?
Could someone please deconstruct and explain what is occurring with require
and permit
here?
推荐答案
控制器中的 params
看起来像一个 Hash,但它实际上是 ActionController::Parameters
,它提供了多种方法,例如require
和permit代码>.
The params
in a controller looks like a Hash, but it's actually an instance of ActionController::Parameters
, which provides several methods such as require
and permit
.
require
方法确保特定参数存在,如果没有提供,require
方法会抛出错误.它返回一个 ActionController::Parameters
的实例,用于传递给 require
的键.
The require
method ensures that a specific parameter is present, and if it's not provided, the require
method throws an error. It returns an instance of ActionController::Parameters
for the key passed into require
.
permit
方法返回一个副本参数对象,只返回允许的键和值.创建新的 ActiveRecord 模型时,仅将允许的属性传递到模型中.
The permit
method returns a copy of the parameters object, returning only the permitted keys and values. When creating a new ActiveRecord model, only the permitted attributes are passed into the model.
它看起来很像以前包含在 ActiveRecord 模型中的白名单,但将其包含在控制器中更有意义.
It looks a lot like the whitelisting that was formerly included in ActiveRecord models, but it makes more sense for it to be in the controller.
这篇关于Rails 4 中的 `params.require(:person).permit(:name, :age)` 是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!