13
12

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-09-03

【概要】

1.結論

2.どういう時に起きるか

3.どのように使うのか

4.ここから学んだこと

1.結論

”redirect_to” と ”unless”を使う!

2.どういう時に起きるか

buy_item_controller.rb
  def edit
    @buy_item = BuyItem.find(params[:id])
  end

例えば、
マイページやマイアカウント、自分の投稿したページを編集する時に"edit"アクションをプログラミングすると思います。

この時に上記のプログラムだけでは、URLに〜〜/〜〜/editと打ち込んでしまえば、ログアウトしているユーザーや、同じアプリケーションにログインしているユーザーでも異なるアカウントを操作できてしまいます。


3.どのように使うのか

buy_item_controller.rb
def edit
    @buy_item = BuyItem.find(params[:id])
   redirect_to root_path unless current_user.id == @buy_item.user_id
end

gem"devise"を使用しているので”current_user.id”が入っています。

”redirect_to root_path”で”トップページに戻る”ようにしています。

”unless current_user.id == @buy_item.user_id”では、”もし現在ログインしているユーザーが該当の商品の出品者ユーザーではなかったら”とプログラムしています。

なので、出品者とログインしているユーザーが違う場合は商品を編集できません。


4.ここから学んだこと

ログアウトしている場合も"edit"で設定しようと思いました。しかし、ログアウトしている場合は範囲がすぎて全てのアクションに設定しないといけません。そのときにbefore_actionを思い出しました。before_actionとexceptを使用して無限ループが起こらないアクション以外(index,show以外)はunlessでプログラミングしてしまえばいいと思いました。

buy_item_controller.rb
 before_action :move_to_index, except: [:index, :show]

  def move_to_index
    redirect_to new_user_session_path unless user_signed_in?
  end


13
12
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
13
12