2012-10-02 28 views
7

如何控制器手動設置驗證錯誤我有3個ActiveRecord的字段的表格。其中一個領域有怎樣的愚蠢和狀態依賴的驗證要求。 (例如,如果對象是在設置嚮導窗體上創建的,我只驗證該字段。)對於某個場

在我的POST處理程序中創建對象時,我想我可以調用errors.add來插入特殊錯誤條件

@foo = Foo.new(params[:foo]) 
if goofy_conditions(params[:foo][:goofy_field]) 
    @foo.errors.add(:goofy_field, "doesn't meet the goofy conditions") 
end 
respond_to do |format| 
    if @foo.save 
    ... 
    else 
    ... redirect back to form (with error fields hilited) 

但是,在控制器中執行@ foo.errors.add()似乎沒有做任何事......如果其他字段通過驗證,它不會阻止save()。

另一種方法是把一個自定義的驗證處理到模型......我知道使用errors.add(:場,「味精」)的作品有很好...但在這種情況下,如何將我的控制器「通行證」信息給驗證器,告訴它該字段是否需要驗證。

+1

把nonpersisted attrbute型號,說的嚮導,設置視情況而定,然後在最終驗證中使用它? –

回答

12

即模型的邏輯。看看custom validations

class GoofyThing < ActiveRecord::Base 
    validate :goofy_attribute_is_goofy 

    def goofy_attribute_is_goofy 
    if goofy_conditions(self.goofy_field) 
     self.errors.add(:goofy_field, "doesn't meet the goofy conditions") 
    end 
    end 
end 

然後它就像任何其他驗證一樣。

編輯

你可以用:if選擇有條件驗證:

attr_accessible :via_wizard 
validate :goofy_attribute_is_goofy, :if => lambda { self.via_wizard } 

,並在你的控制器:

class WizardController < ApplicationController 
    before_filter :get_object, :set_wizard 

    #... 

    def get_object 
    @object = GoofyThing.find(params[:id]) 
    end 

    def set_wizard 
    @object.via_wizard = true 
    end 
end 
+0

啊! attr_accessible:via_wizard是我錯過的。非常感謝你! – jpwynn

相關問題