LoginSignup
2
2

More than 5 years have passed since last update.

Railsで親モデルを保存した時に子モデルを作る

Posted at

ユーザーとプロフィールなどのhas_oneの関係にある場合にレコードを挿入したい場合があると思います。

ActiveRecordにはafter_createというコールバックがあるみたいなのでこんな感じに書いてみました。

class User < ActiveRecord::Base

  after_create :create_profile

  private
    def create_profile
      if self.id
        Profile.create(:name => "name", user_id: self.id)
      end
    end

end

ちなみに after_saveというコールバックもあるみたいですがこちらはモデル作成、更新時に毎回呼び出されるらしいです。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2