我正在尝试将属性组嵌入到我的主要 Person 模型中以帮助保持我的代码井然有序,但 Rails 4 的 Strong Params 阻碍了这一过程。
场景
我有一个 Person
模型和一个 PersonName
模型,如下所示:
class Person
include Mongoid::Document
embeds_one :name, class_name: 'PersonName'
accepts_nested_attributes_for :name
end
class PersonName
include Mongoid::Document
embedded_in :person, inverse_of: :name
# fields here
end
然后我在我的表单中使用 fields_for
帮助程序将 PersonName
属性嵌套在 Person
_form
中:
<%= f.fields_for :name, PersonName.new do |builder| %>
<!-- etc -->
最后我允许 Controller 中的名称属性,以便 Strong Params 允许嵌套属性通过:
def person_params
params.require(:person).permit(:name)
end
问题
它不起作用,我收到错误 Unpermitted parameters: name_attributes
。发生的事情是当我调用 f.fields_for :name ...
时,“_attributes”被附加到 HTML 表单中的字段。例如如果我有一个字段 first_name
那么表单看起来像这样:
<input name="person[name_attributes][first_name] ...>
代替:
<input name="person[name][first_name] ...>
据我所知,这是有意为之的行为,因此似乎 .permit
方法无法正常工作。
尝试变通
我尝试将 Strong Params 行更改为:
params.require(:person).permit(:name_attributes)
但这行不通。使用 permit!
确实 有效,但我不喜欢它,因为据我所知这是一个完全反模式。
我也试过将 :name
到处都改成 :name_attributes
,除了 f.fields_for
助手,因为现在的 HTML 表单有一个实际存在于我的模型上的属性。不幸的是,这导致 f.fields_for :name
产生一个错误,指出 :name
不是一个有效的属性。
最佳答案
Pierre-Louis Gottfrois,是对的,this question解决了我的问题。具体来说,我需要添加:
params.require(:person).permit(name_attributes: [:first_name, ...])
关键是 name_attributes
,后面是我想要允许的符号列表。
关于ruby-on-rails - Strong Params、Nested Attributes 和 Mongoid 似乎因为 *_attributes 形式的后缀而不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18527708/