2012-03-22 38 views
0

在我的控制器動作,我幾乎總是有一個設置閃光燈的錯誤和重定向,像不同的檢查:使用之前的過濾器或停留在控制器?

def create 
    flash[:error] = I18n.t('error.no_resources') and redirect_to research_center_url and return if not resource_report[:has_resources] 

    flash[:error] = I18n.t('error.no_deps') and redirect_to research_center_url and return if not research.fulfil_requirements?(active_city) 
    ... 
end 

這工作得很好,但我想,也許檢查檢查那些在我的模型before_create比擁有更好控制器中的檢查(儘管閃光消息通常應該在控制器中)。

但是,我無法真正把這些檢查放在我的模型中,因爲它們包含非模型相關的信息,我無法真正地正常提取。所以我的問題是,你如何檢查你的控制器的正常應用程序相關的錯誤,這不是例外,必須閃回給用戶?你是否通過模型回調或其他方式在控制器中進行檢查?

回答

1

對許多但不是所有的控制器文件使用before_filter的DRYest方法是使用before_filter和子類ApplicationController。

這使您可以有多個控制器,文件自動共享同一組before_filters

在這個例子中,我調用子類FrontController。你可以使用任何名字。

例如

class FrontController < ApplicationController 
# Used for all "frontend" controllers which have the same checks. 

    before_filter :standard_checks 
    # standard_checks will be a before filter for all controllers that 
    # inherit from this controller class 
end 

然後

class SomeController < FrontController 

    def create 
    .... 
    end 
end 
+0

的問題是,該檢查是不標準。其中一些是關於關卡,其他關於需求,其他關於角色等等。但對於一些具有相同模式的支票,我喜歡+1。 – Spyros 2012-03-22 05:19:55

+0

對我來說,使用過濾器不僅僅是關於DRY代碼,還要保持控制器動作精簡。另外,你對這些Flash消息所做的恰恰就是 - 在你到達那裏之前過濾掉並阻止該操作被調用。 – aceofspades 2012-03-22 05:25:14

相關問題