Rails – Accepts_nested_attributes_for质量分配错误

我目前正在尝试在belongs_to关系上设置一个带有嵌套字段的表单,但是我遇到了一个质量分配错误。 到目前为止,我的代码如下(删除了一些html):

促销型号:

class Sale < ActiveRecord::Base attr_accessible :customer_attributes belongs_to :customer accepts_nested_attributes_for :customer end 

new.html.erb:

 
sales_path do |sale| -%> "customers/form", :locals => {:customer => customer_builder, :form_actions_visible => false} %>

客户/ _form.html.erb

 
"chzn-select"}) %>

我相信这应该允许我创建一个Sale对象和一个嵌套的Customer对象。 发送的参数是(注意包括一些不相关的参数):

 {"utf8"=>"✓", "authenticity_token"=>"qCjHoU9lO8VS060dXFHak+OMoE/GkTMZckO0c5SZLUU=", "customer"=>{"customer_type_id"=>"1"}, "sale"=>{"customer"=>{"features_attributes"=>{"feature_type_id"=>"1", "value"=>"jimmy"}}}, "vehicle"=>{"trim_id"=>"1", "model_year_id"=>"1"}} 

我得到的错误是:

 Can't mass-assign protected attributes: customer 

我可以看到为什么会出现这种情况,因为:客户不在销售的attr_accessible列表中 – 尽管表单不应该发送customer_attributes而不是customer?

任何帮助/建议表示赞赏。

编辑1:据我所知,Sale模型中的attr_accessible应该包含:customer_attributes – 如果有人说不同,请告诉我。

编辑2:我尝试了各种排列,但我似乎无法获取发送customer_attributes的参数而不仅仅是客户 – 也许我错过了一个标签或在上面的表格中使用了错误的标签?

编辑3:我在SO上发现了另一个问题,表明form_for标签上的:url =>部分存在问题 – 问题是指一个表格设置,但我想知道这是否是造成这里问题的原因?

这可能是API文档中的问题:

与attr_accessible一起使用

如果你不小心,使用attr_accessible可能会干扰嵌套属性。 例如,如果上面的Member模型使用attr_accessible,如下所示:

attr_accessible :name

您需要将其修改为如下所示:

attr_accessible :name, :posts_attributes

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#label-Using+with+attr_accessible

我最终得到了答案。 关键是这一行:

 <%= collection_select(:customer, :customer_type_id, CustomerType.all, :id, :value, {}, {:class => "chzn-select"}) %> 

需要更改为:

 <%= customer.collection_select(:customer_type_id, CustomerType.all, :id, :value, {}, {:class => "chzn-select"}) %> 

一旦改变,一切都会到位。