2014-09-24 88 views
0

Activerecod validations guide,說我可以結合條件和驗證發生,如果我所有的條件匹配。「或」運營商在積極記錄驗證

validates :foo, presence: true, if: "bar.present?", if: "baz.present?" 

我有一個場景,當存在「bar」或「baz」時,需要驗證「foo」的存在。

我身邊有做兩個驗證問題的工作:

validates :foo, presence: true, if: "bar.present?" 
validates :foo, presence: true, if: "baz.present?" 

除了尋找醜陋,這個代碼將不能擴展,當我將需要添加更多的選擇。有沒有辦法使用「或」運算符,並提供條件散列,或者使其看起來更好。

回答

1

如果該指南中滾動了大約半頁,你會看到兩個可能的解決方案:Using a stringusing a Proc

的字符串:

validates :foo, presence: true, if: "bar.present? || baz.present?" 

一個Proc(引導使用Proc.new但在紅寶石1.9.3+我們有得心應手proc法):

validates :foo, presence: true, 
    if: proc {|record| record.bar.present? || record.baz.present? } 

或者,如果你正在使用Ruby 2.0+和我一樣,預FER「stabby拉姆達」語法:

validates :foo, presence: true, 
    if: ->(record) { record.bar.present? || record.baz.present? } 
0

最好的做法是定義既響應屬性

validates :foo, presence: true, if: :has_baz_and_bar? 

def has_baz_and_bar? 
    [bar, baz].all?(&:present?) 
end 
方法