如何控制器手動設置驗證錯誤我有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(:場,「味精」)的作品有很好...但在這種情況下,如何將我的控制器「通行證」信息給驗證器,告訴它該字段是否需要驗證。
把nonpersisted attrbute型號,說的嚮導,設置視情況而定,然後在最終驗證中使用它? –