LoginSignup
80

More than 5 years have passed since last update.

posted at

updated at

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

User.rb
has_one :user_password
UserPassword.rb
belongs_to : user

このとき、

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

こうすると、undefined methodbuild' 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でエラーにはまっていたので、目から鱗でした。

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
What you can do with signing up
80