RoR でこのメソッドを記述するにはどうすればよいですか?
if item is nil or item.user!='my_value' redirect_to "/"
次のように呼び出したい:
@item = Item.find(params[:id])
method_described_earlier(@item)
または他の方法。rails pro がどのようにそれを行うのか見たいです。
RoR でこのメソッドを記述するにはどうすればよいですか?
if item is nil or item.user!='my_value' redirect_to "/"
次のように呼び出したい:
@item = Item.find(params[:id])
method_described_earlier(@item)
または他の方法。rails pro がどのようにそれを行うのか見たいです。
指定した一連のコントローラー アクションの前に実行されるbefore_filterを使用する必要があります。例えば:
class SomeController < ApplicationController
before_filter :require_special_item, only: [:myaction, :other_action, ...]
def myaction
# do something with @item
end
private
def require_special_item
@item = Item.find(params[:id])
if @item is nil or @item.user!='my_value'
redirect_to "/"
end
end
end
このメソッドrequire_special_item
は、指定したその他のアクションの前に常に実行myaction
され、見つかったアイテムが要件を満たしていない場合はユーザーをリダイレクトします。