ずみーBlog

元クラゲ研究者(見習い)の92年生まれがエンジニアを目指しながら日々寄り道するブログです。

【Rails】本人のみデータ削除可、ただし一回確認アラートを挟みたい

やりたいことは2つ

  1. 削除アクションは本人のみ可能としたい
  2. 削除する前に一回ブラウザのアラートで最終確認させたい

結果

ルーティング:destroyアクションを追加

Rails.application.routes.draw do
  devise_for :users
  root to: 'items#index'

  resources :items, only: [ :create, :new, :show, :edit, :update, :destroy ]
end

コントローラ:本人以外のリクエストは却下してルートへリダイレクト

プライベートメソッドで定義した:redirect_to_rootにより、例えアドレス手入力でリクエストしたとしても削除アクションが実行されることはありません。

class ItemsController < ApplicationController
  before_action :set_item, only: [:show, :edit, :update, :destroy]
  before_action :redirect_to_root, only: [:edit, :update, :destroy]

  #省略

  def destroy
    @item.destroy
    redirect_to :root
  end

  private

  #省略

  def set_item
    @item = Item.includes([:user, :image_attachment]).find(params[:id])
  end

  def redirect_to_root
    redirect_to :root unless @item.user == current_user
  end
end

ビュー:削除ボタンは本人のみ表示とし、data-confirmで確認アラートを表示

  • if文でcurrent_userが本人かどうかをチェックしています
  • 削除ボタンへのlink_toで、data-comfirmを定義しています
<% if @item.user == current_user %>
  <%= link_to '商品の編集', edit_item_path(@item), method: :get, class: "item-red-btn" %>
  <p class='or-text'>or</p>
  <%= link_to '削除', item_path(@item), method: :delete, class:'item-destroy', data: {confirm: "削除してよろしいですか?"} %>
<% elsif current_user %>
  <% unless @item.respond_to?(:orders) %>
  <%= link_to '購入画面に進む', "#" ,class:"item-red-btn"%>
  <% end %>
<% end %>