ビューに記載していた条件文を可読性、再利用性向上のためモデルに記載する。
※初心者です。ご指摘あればぜひお願いします。
環境
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?を呼び出している。