我有几个这样的模型
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
上面的验证显然不起作用,因为当我从账单表单内的嵌套属性中读取 bill_items 时,属性 bill_item.bill_id 或 bill_item.bill 在保存之前不可用。
那么我该如何去做这样的事情呢?