LoginSignup
0
0

More than 1 year has passed since last update.

rails5 progate 整理メモ

Posted at

ログインしていない場合のアクセス制限

ログインしていないと特定のアクションを作動することができないようにする。
その後ログインページへリダイレクトさせる。

・postsコントローラの全アクション
・usersコントローラのindex, show, edit, updateアクション

その場合にエラーメッセージを表示させる。

まずログインの条件をつけてみる

どうすればよかったか?
if @current_userとかにすれば良かったと思う。
じゃない。
before_actionを使えば良かったと思う。
そこでアクションをする前にメソッドを作動させる。

どのようなメソッドをつけるのか?

ログインしていることがわかればいいからapplication_controllerset_current_userを使えばいいのか? それにonlyをつければいいのかな。
やってみよう。

users_controller.rb
before_action :set_current_user, only:[:index :show :edit :update]

と書いてみた。
がエラーメッセージを表示させなくてはならないことに気づく。
なので新しくメソッドを作成をしようと思う。
どのようなメソッドにすればよいだろうか?

application_controller.rb
  def check_current_user
    if @current_user
    else
      flash[:notice] = "ログインが必要です"
      redirect_to("/login")
    end
  end

ログインの可否を問い、elseでエラーメッセージを表示させるか?
ifも空だし何か腑に落ちない。
その場合@current_userを使いidと照合し...んーーわからん。
答えを見た。

if @current_user == nil
  flash[:notice] = "ログインが必要です"
  redirect_to("/login")
end

@current_userが空の場合を想定するのか。だからelseが必要ないのか。
しかし@current_user == nilに慣れていないので中身が記録がない時にこれを用いるのか。
否定的なif文だな。
if @current_userは肯定的if文だと自分の中で解釈した。
これらを使い分けることによってなんとかでない場合を書けるようになると思う。

authenticate_userというメソッド名は統一なのだろうか?

posts_controller.rb
class PostsController < ApplicationController
  before_action :authenticate_user
.
.
.
end
users_controller.rb
class UsersController < ApplicationController
  before_action :authenticate_user, only:[:index :show :edit :update]
.
.
.
end

ログインしていないユーザーがusersコントローラのindexアクションにアクセスした時に、ログインページへリダイレクトしてください。

すぐに答えを見てしまった。これから頑張る。
onlyの部分がおかしいのがわかる。
ログインページへリダイレクトしてください。と書いてあるためbefore_actionが作動していないことがわかる。

users_controller.rb
class UsersController < ApplicationController
  before_action :authenticate_user, {only:[:index, :show, :edit, :update]}
.
.
.
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