id未在嵌套表单上设置

时间:2011-10-04 04:54:55

标签: ruby-on-rails-3 nested-forms

我有2个模型Order和OrderItem。在订单#new上我嵌套了一个新的OrderItem。当我创建订单时,它会被保存但不会保存OrderItem。看起来orderIid中没有设置order_id。

Order has_many :order_items
accepts_nested_attributes_for :order_items, :reject_if => lambda { |a| a[:product_id].blank? } 
attr_accessible :id, :date, :note, :client_id, :order_items_attributes

在OrderItem中

belongs_to :order 
attr_accessible :product_id, :order_id, :quantity, :color
validates_presence_of :product_id, :order_id, :quantity

在我的视图中

<%= nested_form_for @order do |f| %>
  <%= f.fields_for :order_items do |item| %>
    <%= item.label :product_id %> <%= collection_select(:order_item, :product_id, Product.all, :id, :name, :prompt => 'Select Product') %><br/>
    <%= item.label :quantity %> <%= item.number_field :quantity, :value => '1', :min => '1' %><br />
    <%= item.label :color_id %> <%= collection_select(:order_item, :color_id, Color.all, :id, :name, :prompt => 'Select Color') %>
    <%= item.link_to_remove "Remove this item" %>
  <% end %>
 <p><%= f.link_to_add "Add an item", :order_items %></p>
<% end %>

服务器日志返回"order"=>{"client_id"=>"1", "note"=>"efewfwe", "order_items_attributes"=>{"0"=>{"quantity"=>"1", "_destroy"=>"false"}}}, "commit"=>"Create Order", "order_items"=>{"order_id"=>""}, "order_item"=>{"product_id"=>"12", "color_id"=>"4"}}

不确定第一个零意味着什么,但order_id是nil

1 个答案:

答案 0 :(得分:0)

您正在将OrderItem与has_many :order_items相关联。您的模型是OrderItem。要将复数版本用作order_items,您需要在has_many关联上设置:inverse_of => :order_item