2012-11-08 54 views
1

我有一個類,我正在使用驗證方法來檢查長度,我想注入實際長度到錯誤消息。這可能嗎?活動記錄驗證:長度錯誤信息顯示實際長度?

這裏是我當前的類,我現在用的驗證:

class Something 
    validates :summary, :detail, :length => { 
    :in => 300..500, 
    :too_short => "must have at least %{count} letters", 
    :too_long => "must have at most %{count} letters" 
    } 

和錯誤消息顯示:

2 errors prohibited this job from being saved. 

Summary must have at least 300 letters 
Detail must have at least 300 letters 

但是我想表明:

... 
Summary is only 250 letters and must have at least 300 letters 
... 
+0

有趣的問題@CarsonCole –

回答

1

您的解決方案,你可以通過自定義驗證

validate:summary_length 

def summary_length 
    if self.summary.length < 10 && !self.summary.blank? 
    errors[:base] << "is only #{self.summary.size} letters and must have at least 10 letters" 
    end 
end 
+0

工程很棒。謝謝。 –

0

試試這個,似乎對我很有用:

class Something 
    validates :summary,  
     :in => 300..500, 
     :too_short => "summary is only #{summary.length} and must have at least %{count} letters" 
     # etc. 
    validates :detail, 
     :in => 300..500, 
     :too_short => "detail is only #{detail.length} and must have at least %{count} letters 
     # etc. 
+0

我不能得到那個工作,我不認爲它會。在生產中,變量只能在開始時分析,而不能在對象實例化時分析,除非使用lambda(我不知道在這種情況下如何實現)。但除此之外,我無法讓我認出'總結'。 –