Nested_form_for,field_for无法正常工作

时间:2013-03-31 17:45:03

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2

我的观点是

<h3> Register New Items </h3>
<div class="row">
<div class="span2 offset4">
    <%= nested_form_for @item_category, :url => items_path, :method => :post, :html => { :class => "item_category"} do |f| %>
        <div><%= f.label :item_name %>
        <%= f.text_field :item_name %></div>
        </br>

        <div>
            <%= f.fields_for :item_companies do |f| %>
                  <%= f.label :company_name %>
                <%= f.text_field :company_name %>

     </div>
     </br>

     <%= f.fields_for :item_weights do |f| %>
            <div>
                    <%= f.label :weight %>
                    <%= f.text_field :weight %>
            </div>
            </br>
            <div>
                    <%= f.label :price %>
                    <%= f.text_field :price %>
            </div>
    <%end%>
    <%end%>

    <div><%= f.submit "Submit" %></div>
    <% end %>
</div>

和控制器

def new
  @item_category = ItemCategory.new
  item_company = @item_category.item_companies.build
  item_company.item_weights.build 
end

当我在create操作中应用调试器时,我看到了params[:item_category]的值并且生成了{"item_name"=>"iname", "item_companies_attributes"=>{"0"=>{"company_name"=>"cname", "item_weights_attributes"=>{"0"=>{"weight"=>"20kg", "price"=>"100"}}}}}

ItemCategory.new(params[:item_category])

生成错误

ActiveModel::MassAssignmentSecurity::Error Exception: Can't mass-assign protected attributes: item_companies_attributes.

我错了,以及如何使用此表在三个表中保存价值。

1 个答案:

答案 0 :(得分:0)

您似乎忘了在ItemCategory模型中添加这段代码:

attr_accessible :item_companies_attributes

允许您设置这些属性。