2012-11-28 26 views
0

如何在RoR中編寫此方法?如何在RoR中編寫自定義方法?

if item is nil or item.user!='my_value' redirect_to "/" 

怎麼稱呼它,像這樣:

@item = Item.find(params[:id]) 
method_described_earlier(@item) 

或者其他方式。 想看看rails pro會怎樣做。

回答

0

您應該使用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_itemmyaction你指明任何其他操作之前始終運行,將用戶重定向如果發現項目不符合您的要求。

+0

它聽起來像會做兩個查詢 - 一個是before_filter,另一個是爲了myaction。可以嗎? – user1837021

+0

不,一旦您查詢'before_filter'中的項目並將結果保存在實例變量'@ item'中,假設過濾器沒有調用'redirect_to',則此變量將可用於您的控制器操作。 – cdesrosiers

+0

好的,我應該註釋掉在before_filter下列出的所有操作中的Item.find行嗎?或者沒關係? – user1837021