Ruby on Rails - nested attributes: How do I access the parent model from child model

TMaYaD picture TMaYaD · Apr 10, 2010 · Viewed 8k times · Source

I have a couple of models like so

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

The above validation so obviously doesn't work because when I'm reading the bill_items from nested attributes inside the bill form, the attributes bill_item.bill_id or bill_item.bill are not available before being saved.

So how do I go about doing something like that?

Answer

TMaYaD picture TMaYaD · Feb 19, 2011

This is how I solved it eventually; by setting parent on callback

  has_many :bill_items, :before_add => :set_nest

private
  def set_nest(bill_item)
    bill_item.bill ||= self
  end