我目前正尝试在 belongs_to 关系上设置一个带有嵌套字段的表单,但我遇到了批量分配错误。到目前为止我的代码如下(删除了一些 html):
销售模式:
class Sale < ActiveRecord::Base
attr_accessible :customer_attributes
belongs_to :customer
accepts_nested_attributes_for :customer
end
新的.html.erb:
<div class="container">
<%= form_for :sale, :url => sales_path do |sale| -%>
<%= sale.fields_for :customer do |customer_builder| %>
<%= render :partial => "customers/form", :locals => {:customer => customer_builder, :form_actions_visible => false} %>
<% end -%>
<% end -%>
客户/_form.html.erb
<fieldset>
<label class="control-label">Customer Type</label>
<%= collection_select(:customer, :customer_type_id, CustomerType.all, :id, :value, {}, {:class => "chzn-select"}) %>
</fieldset>
我相信这应该允许我创建一个 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
我明白为什么会这样,因为 :customer 不在销售的 attr_accessible 列表中 - 尽管表单不应该发送 customer_attributes 而不是 customer 吗?
感谢任何帮助/建议。
编辑 1:据我所知,Sale 模型中的 attr_accessible 应该包含 :customer_attributes - 如果有人说不同,请告诉我。
编辑 2:我尝试了各种排列,但我似乎无法获取参数来发送 customer_attributes 而不是简单的 customer - 也许我错过了一个标签或在上面的表格中某处使用了不正确的标签?
编辑 3:我在 SO 上发现了另一个问题,表明 form_for 标签上的 :url =>
部分有问题 - 这个问题是指 formtastic 设置,但我想知道如果这可能是导致这里问题的原因?
最佳答案
这可能是问题所在...来自 API 文档:
Using with attr_accessible
The use of attr_accessible can interfere with nested attributes if you’re not careful. For example, if the Member model above was using attr_accessible like this:
attr_accessible :name
You would need to modify it to look like this:
attr_accessible :name, :posts_attributes
关于ruby-on-rails - Rails - Accepts_nested_attributes_for 批量分配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12064068/