LoginSignup
0
7

More than 3 years have passed since last update.

編集、削除の権限を投稿者だけにしたい

Last updated at Posted at 2020-08-07

バージョン

・ruby 2.5.7
・Rails 5.2.4.3

編集、削除の権限を投稿者だけにしたい

CRUD処理は出来た!
けど、このままだと全ての投稿を編集や削除が出来てしまう状態。

編集、削除の権限を投稿者だけの機能にしたい。

tasks_controller.rb

class TasksController < ApplicationController

  def index
    @tasks = Task.all
  end

  def new
    @task = Task.new
  end

  def create
    Task.create(task_params)
  end

  def show
    @task = Task.find(params[:id])
  end

  def edit
    @task = Task.find(params[:id])
  end

  def destroy
    task = Task.find(params[:id])
    task.delete
end

  def update
    task = Task.find(params[:id])
    task.update(task_params)
  end

  private
    def task_params
        params.require(:task).permit(:title, :content)
    end
end


ユーザーの投稿を守る為に下記のメソッドを使う

unlessはもし〜でなかったらと言う意味。下記でいうと、

もし受け取ったユーザーのIDが、ログインしているユーザー(current_user)のIDと一致しなければ
処理を実行せずリダイレクトで戻しますよっていう意味です。

tasks_controller.rb
  private
    def task_params
        params.require(:task).permit(:title, :content)
    end
    ##以下を追加
   def baria_user
    unless Task.find(params[:id]).user.id.to_i == current_user.id
        redirect_to tasks_path(current_user)
    end
   end
end

before_actionでメソッドを呼び出して、完成!!!

before_actionはコントローラーの全てのアクションが実行される前に実行されるものです。

今回は編集と削除のみの場合で行いたいので、editとupdateとdestroyのみにしています。

tasks_controller.rb

class TasksController < ApplicationController
before_action :baria_user, only: [:edit, :destroy, :update]

  def index
    @tasks = Task.all
  end
0
7
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
7