訪客向其他客人購買物品,因此物品將包含買方和賣方,客人將擁有物品和購買物品。accep_nested_attributes_for對同一張表有兩種關係
class Guest < ActiveRecord::Base
has_many :bought_items, class_name: 'Item', foreign_key: 'buyer_id'
has_many :sold_items, class_name: 'Item', foreign_key: 'seller_id'
accepts_nested_attributes_for :bought_items, :reject_if => lambda { |a| a[:price].blank? } , :allow_destroy => true
accepts_nested_attributes_for :sold_items, :reject_if => lambda { |a| a[:price].blank? } , :allow_destroy => true
end
和
class Item < ActiveRecord::Base
belongs_to :seller, class_name: 'Guest', foreign_key: 'seller_id', inverse_of: :bought_items
belongs_to :buyer, class_name: 'Guest', foreign_key: 'buyer_id', inverse_of: :sold_items
attr_accessor :buyer_id, :seller_id
end
看起來形式回正確發送POST數據(我只編碼迄今購買),爲:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9gR+GZfhT4CffM3ML9LkZaYK+eA85a1oLRG+NRqoRnY=",
"guest"=>{
"guest_number"=>"3",
"bought_items_attributes"=>{
"0"=>{
"item_number"=>"432",
"description"=>"test",
"seller_id"=>"27",
"sales_price"=>"10.0", "id"=>"1"},
"1"=>{
"item_number"=>"",
"description"=>"",
"seller_id"=>"27",
"sales_price"=>"0.0"}
}
},
"commit"=>"Save Changes",
"id"=>"28"}
更新發生的更改guest_number,但不適用於任何嵌套屬性。模型設置有問題嗎?
這是Rails 3.1。
哦,我的。這確實是個問題。我一直在尋找*小時*!嘆息...非常感謝你的幫助。 – Brenda 2011-12-22 18:06:33