Create associated records in model after create

1.1k Views Asked by At

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?

1

There are 1 best solutions below

3
On

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