LoginSignup
1
1

More than 1 year has passed since last update.

Rails ログインユーザーが、URLを入力しても特定のページに遷移できないようにする

Posted at

作成していた投稿アプリで
「ログインしているユーザー以外が投稿した記事の編集ページに飛ぼうとすると、トップページに遷移する」
という機能がありました。

Aさんが投稿したid=1という記事の編集(edit)にBさんがアクセスできないようにする、ということですね。

実装しなきゃいけないのは、単純にeditメソッドだけでなく、ログインユーザー以外がeditページにアクセスした時、という条件を付けなければいけないということ。

def edit
    @prototype = Prototype.find(params[:id])
    unless current_user.id == @prototype.user_id
      redirect_to root_path
    end
  end

解説します。
今回でいう記事はprototypeですね。

editアクションが実行された時、prototypeから該当のidをfindで見つけて、@prototypeに格納します。

で、unlessで

unless current_user.id == @prototype.user_id
      redirect_to root_path
end

という条件をつけました。
deviseを使用しているので、current_userとなりますが、要はログインユーザーと@prototypeのユーザーIDが一致しない時はリダイレクトでroot_pathに戻されます。

参考文献
ログインユーザーが、URLを入力しても特定のページに遷移できないようにする

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