2
4

More than 3 years have passed since last update.

[Rails]ログインidと投稿者が一致した時の条件式をモデルに書き出す

Last updated at Posted at 2020-01-06

ビューに記載していた条件文を可読性、再利用性向上のためモデルに記載する。
※初心者です。ご指摘あればぜひお願いします。

環境

Rails 5.2.3
mysql 5.7.28
gem Sorcery使用

変更前

boards_controller
def index
    @boards = Board.all.includes(:user).recent
end
_boards.html.erb
<% if current_user.id == board.user_id %>
  <div style='display: inline; float: right;'>
    <%= link_to icon('fas', 'pen'), edit_board_path(board), id: :"button-edit-#{board.id}" %>
    <%= link_to icon('fas', 'trash-alt'), board_path(board), id: :"button-delete-#{board.id}",
                method: :delete, data: { confirm: '削除してよろしいですか?' } %>
  </div>
<% else %>
.
.
.

変更後

user.rb
def own_board?(board)
  self.id == board.user_id
end

userモデルにown_board?というメソッドを定義し引数でboardを引き渡す。
boardの中はboards_controllerのindexアクションの中身が入っている。
self.idにはログインしているユーザーid、board.user_idにはboardインスタンスのuser_idが入っており、この両者のidが一致した場合という条件文となる。

index.html.erb
<div class="row d-flex">
  <%= render @boards %>
</div>

indexではパーシャルを読み込んで

[参照]
まるで魔法だな(パーシャルをrenderし繰り返し処理をする)

_boards.html.erb
<% if current_user.own_board?(board) %>
  <div style='display: inline; float: right;'>
    <%= link_to icon('fas', 'pen'), edit_board_path(board), id: :"button-edit-#{board.id}" %>
    <%= link_to icon('fas', 'trash-alt'), board_path(board), id: :"button-delete-#{board.id}",
                method: :delete, data: { confirm: '削除してよろしいですか?' } %>
  </div>
<% else %>
.
.
.

current_userというインスタンスにはログインユーザーの情報が入っていて(Sorcery内でメソッド定義)このインスタンスメソッドとしてown_board?を呼び出している。

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