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

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


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

  has_many :bill_items, :before_add => :set_nestprivate  def set_nest(bill_item)    bill_item.bill ||= self  end


In Rails 4 (didn't test on earlier versions) you can access the parent model by setting the inverse_of option on has_many or has_one:

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

Documentation: Bi-directional associations


The bill_item.bill should be available , you could try to do a raise self.bill.inspect to see if it's there or not, but i think the problem is elsewhere.