LoginSignup
0
0

More than 1 year has passed since last update.

rails5 progate 整理メモ 投稿者権限

Posted at

投稿者だけが編集できるようにしよう(1)

他のユーザーが編集できないようにする

投稿者だけが編集,削除をできるようにする

@post.userのidと、@current_userのidを比較し、等しい場合にのみ編集・削除リンクを表示するようにする。

      <% if @post.user_id == @current_user.id %>
        <div class="post-menus">
          <%= link_to("編集", "/posts/#{@post.id}/edit") %>
          <%= link_to("削除", "/posts/#{@post.id}/destroy", {method: "post"}) %>
        </div>
      <!-- 以下の<% %>を使ってif文のendを追加してください -->
      <% end %>

@current_userapplication_controller.rbで設定されているため書くコントローラがアクションを作動させる前にこのコントローラを通るのでこのインスタンス変数は全てのコントローラで使うことができる。
(自信ないです。)

投稿者だけが編集できるようにしよう(2)

リンクを表示不可にしてもURLで簡単にアクセスすることができる。
なので今回も
before_actionを使いそれを防ぐ。

なんでこれで防げるかというと、(多分)

routes.rbをみてもらうとわかるが、特定のパスを入力した後、コントローラーのアクションが動くから
このアクションが作動する前にコントローラで設定したメソッドbefore_actionで止めることができるからだ。
これは作動を防ぎたいコントローラのアクションのために使うのでそのコントローラーでメソッドを書く。(機能別)
また全コントローラーで使うのはapplication_controller.rbで書く。(ログイン機能など)

メソッドを書いた

posts_controller.rb
class PostsController < ApplicationController
  before_action :authenticate_user
  # before_actionでensure_correct_userメソッドを指定してください
  before_action :ensure_correct_user, {only:[:edit, :update, :destroy]}
  
.
.
.
  def ensure_correct_user
    @post = Post.find_by(id: params[:id])
    if @post.user_id != @current_user.id
      flash[:notice] = "権限がありません"
      redirect_to("/posts/index")
    end
  end

これでurlからのアクセスを防げるのか?
成功!

0
0
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
0