いつ使うの
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
ではまた!