0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Rails] 直打ち禁止方法

Last updated at Posted at 2021-03-15

直打ち禁止とは?

instagram風アプリなどの作成時に、投稿者のみ、編集や削除ができるようにすることです。
current_user などで view のみを制御してもURLに直接 https:///XXX/edit などを打ち込むと投稿者以外のアカウントでも編集できてしまいます。これを出来なくすることを直打ち禁止といいます。

前提

railsで devise を導入していること。

実装方法

application_controller に、before_actionメゾットを追記します。

application_controller
before_action :configure_permitted_parameters, if: :devise_controller?

次に、直打ち禁止させたいcontrollerページに以下を追記します。
今回は post_controller.rb という名前の controller ページに追記していきます。

post_controller.rb
before_action :authenticate_user!
before_action :ensure_correct_user, { only: [:edit, :update, :destroy] }

authenticate_user! はログインしているユーザーのみ使えるようにするメゾットです。(devise で使えるようになるヘルパーメソッド)
before_action :ensure_correct_user を追記し、 { only: [:XXX] } に直打ち禁止したいアクションを追記します。今回は edit, update, destroy を追記しました。

また、同じcontrollerページ(今回は post_controller.rb )の private より上に下記のコードを追記します。

post_controller.rb
def ensure_correct_user
    @post = Post.find_by(id: params[:id])
    return unless @post.user_id != current_user.id

    redirect_to posts_path
  end

投稿したユーザーとログインしているユーザーのidが違うとき、 posts_path にリダイレクトするようになります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?