Ich habe ein paar Modelle wie soRuby on Rails - verschachtelte Attribute: Wie kann ich das übergeordnete Modell Modell von Kind Zugang
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
Die obige Validierung so offensichtlich nicht, weil nicht funktioniert, wenn ich lese die bill_items von verschachtelten Attributen innerhalb des Rechnungsformulars, die Attribute bill_item.bill_id oder bill_item.bill sind vor dem Speichern nicht verfügbar.
Also, wie mache ich so etwas?
Ich löste dies, indem ich einen Aufruf zurück zu der Assoziation hinzufügte,: before_add =>: set_nest – TMaYaD