LoginSignup
1
3

More than 3 years have passed since last update.

before_action ❏Rails❏

Last updated at Posted at 2019-11-26

いつ使うの

before_actionを使えば、すべてのアクションのが実行される前に指定したメソッドを呼び、共通の処理を実行することができます。

使い方

before_action :メソッド名

これをコントローラーの一番上の書きます。



オプションとしてonlyとexceptがあります。

only: [:アクションA]
→アクションAのときのみ

except: [:アクションB]
→アクションB以外のとき

tweets_controller.rb
class TweetsController < ApplicationController

  before_action :move_to_index, except: [:index]

  def index
    @tweets = Tweet.all
  end

  def new
  end

  中略

  def move_to_index
    redirect_to action: :index unless user_signed_in?
  end
end

indexアクション以外のとき、まず初めにmove_to_indexを実行します。

move_to_indexはログインしていない場合に、indexアクションへ遷移させるというものです。
これで、ログインしていないと新規投稿などができなくなります。





ちなみにdeviseがインストールされている場合は、
authenticate_user!というヘルパーメソッドを使って省略できます。

tweets_controller.rb
class TweetsController < ApplicationController
  before_action :authenticate_user!, except: [:index]

  def index
  end

  def new
  end

  中略

end



deviseのヘルパーメソッドはこちらへ

https://qiita.com/drafts/5c3c4abd35af82b3e7c3



ではまた!

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