强参数允许嵌套属性的所有属性 [英] strong parameters permit all attributes for nested attributes

查看:31
本文介绍了强参数允许嵌套属性的所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

强参数中有没有办法允许nested_attributes模型的所有属性强>?这是一个示例代码.

Is there a way in strong parameters to permit all attributes of a nested_attributes model? Here is a sample code.

class Lever < ActiveRecord::Base
 has_one :lever_benefit
 accepts_nested_attributes_for :lever_benefit
end

class LeverBenefit < ActiveRecord::Base
  # == Schema Information
  #  id          :integer          not null, primary key
  #  lever_id    :integer
  #  explanation :text
end

对于杠杆强参数,我目前正在写这个

def lever
 params.require(:lever).permit(:name,:lever_benefit_attributes => [:lever_id, :explanation])
end

有没有一种嵌套属性的方法,我可以编写允许所有属性,而无需明确给出属性名称,如lever_idexplanation?

Is there a way for nested attributes i can write to permit all attributes without explicitly giving the attributes name like lever_id and explanation ?

注意:请不要将此问题与 permit!permit(:all) 混淆,这是针对 允许所有嵌套属性

Note: Please don't get confused with this question with permit! or permit(:all) this is for permitting all for nested attributes

推荐答案

强参数的全部意义在于它的名字:让你的输入参数变强.
允许所有参数将是一个非常糟糕的主意,因为它会允许任何人插入您不一定希望您的用户更新的值.

The whole point of strong parameters is in its name: make your input parameters strong.
Permitting all the parameters would be a very bad idea, as it would permit anyone to insert values you don't necessarily want to be updated by your users.

在您给出的示例中,您提到了您当前需要提供的两个参数:
[:lever_id, :explanation].

In the example you give, you mention the two parameters you currently need to provide:
[:lever_id, :explanation].

如果您允许所有参数,则有人可以更改任何其他值.
created_atlever_id 例如.

If you permitted all the parameters, it would be possible for somebody to change any other value.
created_at, or lever_id for example.

这肯定是一个安全问题,这就是您不应该这样做的原因.明确指定所有属性在执行时可能看起来很无聊.
但这是确保您的应用程序安全所必需的.

This would definitely be a security issue and this is why you should not do it.
Explicitely specifying all your attributes might seem boring when you do it.
But this is necessary to keep your application secure.

编辑:对于那些反对这一点的人.这可能不是您正在寻找的答案,但却是您需要的答案.
将所有嵌套属性列入白名单是一个巨大的安全漏洞,强参数试图用它来保护您,而您正在删除它.
看看是什么导致了构建 strong_params,以及不使用它对你有什么危害:https:///gist.github.com/peternixey/1978249

Edit: For people downvoting this. This may not be the answer you're looking for, but it is the answer you need.
Whitelisting all nested attributes is a huge security flaw that strong params is trying to protect you with, and you're removing it.
Take a look at what lead to building strong_params, and how not using it can be bad for you: https://gist.github.com/peternixey/1978249

这篇关于强参数允许嵌套属性的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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