あきくもちゃのブック
mindiaあきくもちゃのブック見出し語

rails-before_filter

秋雲茶 · 2012-03-11 更新

アクションを実行する前に特定の処理を行いたい場合に指定。

>|ruby|
class HogeController < ApplicatonController
before_filter :fuga

private

def fuga
...
end

end
||<

例えば、サブミットに確定ボタンと、キャンセルボタンを実装したとして、キャンセルを押した時に確定時とはリダイレクトを変えたい場合。

>|ruby|
before_filter :check_for_cancel, only: [:create, :update]

...

private

def check_for_cancel
unless params[:cancel].blank?
redirect_to '/controller/action'
end

end
||<

※only: ~ のくだりは、ビュー側の action="~" の値になる。