LoginSignup
1
1

More than 3 years have passed since last update.

Railsのhas_oneで関連テーブルの保存

Last updated at Posted at 2019-10-11

has_oneで関連させて保存させる方法につまったので書いておきます。
他のやり方(createを2回使う)もあったのですが、create!しても例外をキャッチできない?感じだったので、こちらの書き方にしました。

app/controllers/users_controller.rb

def create
    @user = User.create(user_params)
    # この行のcreate_articleは状況に応じてprofile部分を読みかえて使います。
    @profile = @user.create_profile(profile_params)
end
app/models/user.rb
has_one :profile
app/models/profile.rb
belongs_to :user

参考サイト
Active Record の関連付け - Rails ガイド

1
1
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
1
1