0
我使用了很多自己的驗證方法來比較一個關聯到另一個關聯的數據。我注意到,在嘗試調用任何對象之前,我經常檢查我的關聯不是零,但我也驗證了他們的存在,所以我覺得我的無效檢查是多餘的。這裏有一個例子:是否可以對驗證進行分組?
class House < ActiveRecord::Base
has_one :enterance, :class => Door
has_one :exit, :class => Door
validates_presence_of :enterance, :exit
validate :not_a_fire_hazard
def not_a_fire_hazard
if enterance && exit && enterance.location != exit.location
errors.add_to_base('If there is a fire you will most likely die')
return false
end
end
end
我覺得我通過在自己的驗證中檢查輸入和退出的存在來重複自己。
有沒有更多的「The Rails Way」來做到這一點?
入口和出口會退出服務器進程。退出是停止虛擬機的內核方法。 Ooops – 2010-06-11 00:37:48
+1弗朗索瓦,我沒有在我的帖子中提到。不過,我認爲這個想法依然存在。 – randombits 2010-06-11 00:58:17
出口處的羊羣,這只是我編造的一個例子。我不知道這將如何解決我的問題,就好像not_a_fire_hazard在驗證鏈中,並且入口或foo是零,我仍然會做nil.location。既然驗證是同時進行的(也許它不會在這種情況下?),即使沒有通過entrance_or_foo,也不會調用not_a_fire_hazard嗎? – lambdabutz 2010-06-11 13:26:33