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?

4

1 に答える 1

2

Railsコールバックを使用したいと思うでしょう。この場合after_createは、元のオブジェクトが正常に作成された後に実行されます。このようなもの:

class MyModel

  after_create :create_associations

  def create_associations
    myass = MyAssociation.new
    myass.mymodel_id = self.id
    myass.save
  end
end
于 2015-05-28T20:17:31.517 に答える