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】URL直打ち対策

Last updated at Posted at 2021-08-05

忘備録として残します。

URL直打ちとは、アドレスバーにURLを直接打ち込むことです。
直打ちを禁止しないと、だれでもプロフィールや投稿内容を編集できてしまうので対策しておきましょう。

posts_controller.rb

直打ちをさせたくないコントローラーを開き、before_actionで、特定のアクションの直打ちを制限します。

app/controllers/posts_controller.rb
class PostsController < ApplicationController
  before_action :authenticate_user!
  before_action :correct_post,only: [:show, :edit] #追記

  def show
    @post = Post.find(params[:id])
  end

  def edit
    @post = Post.find(params[:id])
  end

  private

 # ここから追記
  def correct_post
    @post = Post.find(params[:id])
    unless @post.user.id == current_user.id
      redirect_to root_path  #直打ちした時リダイレクトするパスを指定
    end
  end
 # ここまで
end

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?