2014-02-27 58 views
0

在rails 4.0.0中,我需要驗證我的模型上是否存在attribute_a或模型上是否存在attribute_b。其中一個必須存在,而且他們兩個不能同時存在。Rails驗證attribute_a是否存在OR attribute_b存在

我該如何編寫驗證?

+1

看起來像一個重複: http://stackoverflow.com/questions/ 2134188 /驗證一場或另一種異物 在那裏尋找答案。 – Coenwulf

回答

0
validates_numericality_of :charge, allow_nil: true 
validates_numericality_of :payment, allow_nil: true 


validate :charge_xor_payment 

private 

def charge_xor_payment 
    if !(charge.blank?^payment.blank?) 
    errors.add(:base, "Specify a charge or a payment, not both") 
    end 
end 

另一種方式:

a或b姓氏是強制性

validate :a_or_b 
def a_or_b 
    if a == "Last Name" or a.blank? 
     errors.add(:a, "cant blank") 
     errors.add(:b, "cant blank") 
    end 
end 

source

+1

你真的只是複製從http://stackoverflow.com/questions/2134188/validate-presence-of-one-field-or-another-xor的答案沒有任何信貸來源?如果它不是原創的,請指出你的答案。 – Coenwulf