LoginSignup
0
1

More than 3 years have passed since last update.

条件分岐と演算子について

Last updated at Posted at 2021-04-18

フリマアプリの商品詳細画面で

条件分岐1

解答1

ログインかつ出品者

こちらには編集雨ボタンと削除ボタン表示

<% if user_signed_in? && current_user.id == @item.user_id %>

<% end %>

devise導入で使用できるメソッド

メソッド 用途
user_signed_in? ユーザーがサインイン済かどうかを判定
current_user サインインしているユーザー情報を取得

@item.user_id 今ログインしている人のuser_idがitemテーブルにあれば出品者ということになる。

*before_action :authenticate_user! コントローラーに設定して、ログイン済ユーザーのみにアクセスを許可する.

別解

可読性を高めるために

<% if user_signed_in? %>
  <% if current_user.id == @item.user_id %>

  <% end %>
<% end %>

条件分岐2

ログインはしているが出品者ではない投稿者

購入ボタン表示

<% elsif user_signed_in? && current_user.id != @item.user_id %>

別解2

<% elsif user_signed_in? %>
  <% if current_user.id != @item.user_id %>

  <% end %>
<% end %>
0
1
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
1