Open hirolibe opened 4 months ago
◯profileの有無で「参照」or「新規作成」の条件分岐したメソッドを適用する
app/models/user.rb
def prepare_profile
profile || build_profile
end
app/controllers/profiles_controller.rb
def edit
@profile = current_user.prepare_profile
end
def update @profile = current_user.prepare_profile @profile.assign_attributes(profile_params) if @profile.save redirect_to profile_path, notice: 'プロフィール更新!' else flash.now[:error] = '更新できませんでした' render :edit end end
profiles_controller.rbにnewとcreateアクションが不要である理由がわからない user作成した時点では、
@profile
インスタンスがnilクラスとなるので、ビューで情報を取得できない userを新規作成したときに、プロフィールも同時に作成する?