0

I have a model, MyModel, which should, after it is created, created associated records of type MyAssociation. I need to run code like the below after a create on the MyModel:

myass = MyAssociation.new
myass.mymodel_id = self.id
myass.save

What is the best method to accomplish this?

steventnorris
  • 5,656
  • 23
  • 93
  • 174

1 Answers1

2

You're going to want to use Rails callbacks, in this case after_create which will execute after successful creation of the original object. Something like this:

class MyModel

  after_create :create_associations

  def create_associations
    myass = MyAssociation.new
    myass.mymodel_id = self.id
    myass.save
  end
end
MCBama
  • 1,432
  • 10
  • 18