LoginSignup
0
0

More than 3 years have passed since last update.

ログイン状態且つ住所テーブルにデータが登録してある場合としてない場合の条件分岐

Posted at
def new
    if current_user && Address.find_by(user_id: current_user.id).present?
      @address = Address.find_by(user_id: current_user.id)
      render action: :edit
    else
      @address = Address.new
    end
if current_user && Address.find_by(user_id: current_user.id).present?

2行目 ...presentメソッドはオブジェクトのレシーバーの値が存在すればtrue、存在しなければfalseを返すメソッド。if文などの条件分岐でよく使用するので覚えておきたい。
current_user.idと一致するuser_idが存在すればeditアクションが動く。
ちなみに(renderで同じコントローラーのアクションが動かせるのは本日知りました)

6行目...current_user.idと一致するuser_idが存在しなければnewアクションがそのまま動くので新規登録となる。

0
0
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
0
0