accepts_nested_attributes_for与同一个表有两个关系

时间:2011-12-22 14:07:27

标签: ruby-on-rails ruby-on-rails-3.1 nested-attributes

客人从其他客人处购买物品,因此物品将包含买家和卖家,并且客人将购买物品并购买物品。

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。

2 个答案:

答案 0 :(得分:1)

如果reject_if属性为空白,那么您的price数据块会拒绝数据,而您的帖子数据则为sales_price

你也想摆脱那个attr_accessor,如lucapette指出的那样。

答案 1 :(得分:0)

attr_accessor肯定是个问题。也许你会使用attr_accessible