135
85

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

has_one関係のあるモデルをbuildするときは注意

Last updated at Posted at 2018-03-22
User.rb
has_one :user_password
UserPassword.rb
belongs_to : user

このとき、

User_controller.rb
@user = User.new
@user.user_password.build

こうすると、undefined method build' for nil:NilClass`というエラーがでる。
このやり方は、has_many(1対多)の関係にあるモデルにのみ使用可能。

has_one(1対1)の関係にある場合のbuildは、

User_controller.rb
@user = User.new
@user.build_user_password

となる。
インスタンス名.build_アソシエーション名が正しい、has_one関係にあるbuildのやり方

ずっと、@user.user_password.buildでエラーにはまっていたので、目から鱗でした。

135
85
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
135
85

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?