Ruby on Rails - 嵌套属性:如何从子模型访问父模型

TMa*_*YaD 20 ruby-on-rails nested-attributes

我有几个这样的模特

class Bill < ActiveRecord::Base
  has_many :bill_items
  belongs_to :store

  accepts_nested_attributes_for :bill_items
end

class BillItem <ActiveRecord::Base
  belongs_to :product
  belongs_to :bill

  validate :has_enough_stock

  def has_enough_stock
    stock_available = Inventory.product_is(self.product).store_is(self.bill.store).one.quantity
    errors.add(:quantity, "only #{stock_available} is available") if stock_available < self.quantity
  end
end
Run Code Online (Sandbox Code Playgroud)

上面的验证显然不起作用,因为当我从bill表单中的嵌套属性中读取bill_items时,属性bill_item.bill_id或bill_item.bill在保存之前不可用.

那我该怎么做呢?

TMa*_*YaD 18

这就是我最终解决的问题; 通过在回调上设置父级

  has_many :bill_items, :before_add => :set_nest

private
  def set_nest(bill_item)
    bill_item.bill ||= self
  end
Run Code Online (Sandbox Code Playgroud)


yen*_*rak 8

在Rails 4中(未在早期版本上测试),您可以通过设置inverse_of选项on has_many或访问父模型has_one:

class Bill < ActiveRecord::Base
  has_many :bill_items, inverse_of: :bill
  belongs_to :store

  accepts_nested_attributes_for :bill_items
end
Run Code Online (Sandbox Code Playgroud)

文档:双向关联