has_oneでbuildメソッドを使うときの書き方
アソシエーションは以下のとおりで、1対1の関係
class User < ApplicationRecord has_one :user_profile, dependent: :destroy end
class UserProfile < ApplicationRecord belongs_to :user end
class UserProfilesController < ApplicationController # 略 def create @user_profile = current_user.user_profile.build(user_profile_params) # 略
こんな感じで、ログインしているユーザー(current_user
)が、プロフィール(UserProfile
)をbuild
…と記述したらエラー。
NoMethodError at /user_profiles undefined method `build' for nil:NilClass Hint: Something is `nil` when it probably shouldn't be.
has_one
で関連付けをしているとき、
build_association
という書き方になる。
@user_profile = current_user.build_user_profile(user_profile_params)