0

I have the below models:

class Foo < ActiveRecord::Base
    has_many :bars
end

class Bar < ActiveRecord::Base
    belongs_to :foo
end

In the business logic, when initializing an object foo f = Foo.new three bars need to be initialized, too. How can I do this?

3 Answers 3

4

You can use after_create(after calling Foo.create) or after_initialize(after calling Foo.new) in your Foo.rb

after_create :create_bars

def create_bars 
  3.times  do
   self.bars.create!({})
  end
end

Or:

after_initialize :create_bars

def create_bars 
  3.times  do
   self.bars.new({})
  end if new_record?
end
Sign up to request clarification or add additional context in comments.

2 Comments

I read that in rails 4, after_initialize is deprecated. Is it this possible? I can't use after_create because this method save on database. In my case, I will save after
Actually, this callback is called only when the object is instanciated from the database (meaning, it's a duplicate of 'after_find' callback). So, look at my updated answer.
3

You can:

  • set an after_initialize callback that initializes the Bar instances
  • set additional :autosave option on the has_many association to assure child Bar instances get saved when saving the parent foo

The code will then look like this:

class Foo < ActiveRecord::Base
  has_many :bars, autosave: true

  after_initialize :init_bars

  def init_bars
    # you only wish to add bars on the newly instantiated Foo instances
    if new_record?
      3.times { bars.build }
    end
  end

end

You can add the option dependent: :destroy if you wish Bar instances get destroyed when you destroy the parent Foo instance.

Comments

0

you can define that in the initialize method of the Foo class. Initializer block will run whenever the Foo object gets created and you can create the related objects in that method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.