2013-02-24 42 views
0

我正在使用Rails 3.2.11。我有一個動作(表演),如果模型中的某個屬性未設置,我想禁用該動作。現在我正在處理這個問題:僅在模型具有某些屬性集時啓用動作

def show 
    @model = Model.find(params[:id]) 
    if [email protected] 
     raise ActionController::RoutingError.new('Something bad happened') 
    end 
end 

這是可以接受的還是有更好的方法來處理這種情況?我希望行爲與用戶試圖訪問不存在的記錄時相同。

回答

-1

是的,這是可以接受的。我會親自將條件寫成一行。

raise ActionController::RoutingError.new('Something bad happened') unless @model.attribute? 

一個很好的資源,可供選擇的方法來處理:not_found響應this question

0

我更喜歡使用這種邏輯在的before_filter,所以你的節目的行動將是乾淨的:

before_filter :check_attribute 

... 

def show 
    # you can use straight @model here 

end 
... 

private 

def check_attribute 
    @model = Model.find(params[:id]) 
    if [email protected] 
    raise ActionController::RoutingError.new('Something bad happened') 
    end 
end 

這樣你也可以將其用於其他行動。

+1

我想你的意思是「before_filter」 – mockaroodev 2013-02-24 22:59:48

+1

此外,你可以限制這個過濾器在過濾器上使用'only'或'except'選項的方法:'before_filter:check_attribute,:only =>:show' – 2013-02-24 23:06:16

相關問題