2010-04-21 115 views
0

場景:基於關聯模型的數據驗證和ActiveRecord模型?

Given that a model called Edition has its community feature enabled 

I want all Records under that Edition to validate for the community field 

When the community feature is disabled, the community field will NOT be validated 

基本上,我試圖寫在ActiveRecord的級別定義驗證函數,將檢查父版本具有正確的真/假值。

但我不知道處理這個問題的最佳方法。我的直覺是這樣,但是我以爲我會得到社區的反饋:

class Record < ActiveRecord::Base 
validate edition_has_communities? 

private 
    def edition_has_communities? 
    if self.edition.communities_enabled 
     if community.blank? 
      errors.add(:community, "must be filled out for this Edition") 
     end 
    end 
    end 
end 

我擔心的是,這種方法依賴於與該版的相關驗證之前被確定,而且可能並不總是是這樣的。這是否應該在前端進行驗證?

想法?

回答

0

看起來像這樣對我來說很好,如果你擔心版本關聯是否被定義,爲什麼不加一張支票?
if self.edition and self.edition.communities_enabled
對我來說,這是不是在前端驗證,我認爲你是正確的把它放在模型中。有沒有真正應該在前端驗證的東西?

+0

哈哈太過分了。 :)我會繼續前進,並按原樣進行拍攝。 (和你的權利,我可以只加一張支票..有時我發誓我無法看到樹林的森林:) – 2010-04-22 02:13:00

+0

它的工作..大聲笑感謝您的反饋意見。 – 2010-04-22 15:47:31

+0

甜。我並不是在試圖討論是否應該在前端驗證什麼東西 - 我真的很好奇,人們是否認爲應該有這樣的事情。很高興它的工作 - 有時你需要的是另一雙眼睛。 – bergyman 2010-04-29 16:31:35