4
9

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.

model同士がhas_oneとbelongs_toの関連の時はbuildが使えないので build_○○○を使う

Last updated at Posted at 2018-12-10

#UserモデルとProfileモデルで1対1の関連付けを行う。

profile.rb
class Profile < ApplicationRecord
  belongs_to :user
end
user.rb
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :memos
  has_one :profile
end

#profiles_controllerにnewアクション、createアクションを定義

ここで大事なのは、1対1の関連の時はbuildではなくbuild_モデル名の書き方になる

profiles_controller.rb

  def new
      #@profile = current_user.profile.buildだと動かない。
     @profile = current_user.build_profile
  end
  
  def create
     @profile = current_user.build_profile(profile_params) 
     @profile.assign_attributes(profile_params) #.assign_attributesは変更するだけで保存はしない。フォームから送られてきた値(profile_params)を保存できなかった場合、記入していた文字がそのまま残ってrenderされる
     if @profile.save
       flash[:success] = "名前を登録しました"
       redirect_to root_url
      else
       flash[:danger] = "名前の登録に失敗しました"
       render :edit
     end
  end

これで通常通り動きます。
そんなん知らへんやん普通、、
そんなん言うというてや、、

参考
https://qiita.com/SpicyCoffee/items/cfeb728c63f946976cc0
https://gist.github.com/seak0503/7291012e7e99fc8aca80

4
9
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
4
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?