[英]How do you access params[:model][:field] in Rails 4?
From what I understand... 据我了解...
form_for @model
, params[:model]
is available when the form is submitted. 如果您有一个form_for @model
,则在提交表单时可以使用params[:model]
。 Furthermore, if the form has 2 attributes attr1
and attr2
, params[:model][:attr1]
and params[:model][:attr2]
are available when the form is submitted. 此外,如果表单具有2个属性attr1
和attr2
,则在提交表单时可以使用params[:model][:attr1]
和params[:model][:attr2]
。 model_params
that says params.require(:model).permit(:attr1, :attr2)
. 在Rails 4中,您应该编写一个model_params
params.require(:model).permit(:attr1, :attr2)
方法。 model_params
like so: Model.new(model_params)
. 然后,您可以像这样使用model_params
: Model.new(model_params)
。 However, what do you do if you only need one of the fields from the form? 但是,如果只需要表单中的字段之一,该怎么办? Like if you only needed params[:model][:attr1]
? 就像您只需要params[:model][:attr1]
吗?
Example: 例:
def create
@user = User.new(user_params)
if @user.save
# need access to params[:user][:password] here
redirect_to root_url, :notice => "Signed up!"
else
render :new
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
The gem responsible for this behaviour is strong_parameters
. 负责此行为的gem是strong_parameters
。 The permit()
method decides what to pass on to the model based on the attributes you pass to it. permit()
方法根据您传递给模型的属性来决定传递给模型的内容。
In your case, you passed it :attr1
and :attr2
: 在您的情况下,您将其传递给:attr1
和:attr2
:
params.require(:model).permit(:attr1, :attr2)
This means the model will have attr1
and attr2
set to whatever values were passed from the form. 这意味着该模型会将attr1
和attr2
设置为从表单传递的任何值。
If you only wanted to set attr1
, just remove attr2
from the permit()
call. 如果只想设置attr1
,只需从attr2
permit()
调用中删除attr2
。
params.require(:model).permit(:attr1)
You model will not have attr1
set, but not attr2
. 您的模型将不会设置attr1
,但不会设置attr2
。 It's that simple. 就这么简单。
You can even permit everything (not recommended) by calling permit!
您甚至可以致电permit!
允许一切(不推荐) permit!
with a bang and no arguments. 一声巨响,没有争论。
You can read more about this behaviour on the gem's Github project page . 您可以在gem的Github项目页面上了解有关此行为的更多信息。
If you need access to params[:user][:password]
in the controller... well, you just accessed it in your example. 如果您需要访问控制器中的params[:user][:password]
...那么,您只是在示例中访问了它。 You accessed it by typing params[:user][:password]
. 您通过输入params[:user][:password]
来访问它。
Nothing prevents you from accessing the params hash directly. 没有什么可以阻止您直接访问params哈希。 strong_parameter's job is to prevent you from mass assigning a hash to a model, that's all. strong_parameter的工作是防止您将大量哈希分配给模型,仅此而已。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.