私はそのようなモデルをいくつか持っています
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 が保存される前に使用できないため、上記の検証は明らかに機能しません。
では、どうすればそのようなことをすることができますか?