2010-01-25 120 views

回答

111

如果條件語句添加到numericality驗證,像這樣你的代碼將工作:

class Transaction < ActiveRecord::Base 
    validates_presence_of :date 
    validates_presence_of :name 

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


    validate :charge_xor_payment 

    private 

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

end 
+0

這就是所謂的完美的答案。謝謝@Semanticart – 2016-04-29 13:00:24

+0

功能很好。但是,我無法獲取表單頁面上顯示的錯誤。除非我在我的_form.slim上做'= @ invoice.errors [:base] [0]'之類的東西。有什麼建議麼? – 2016-05-18 17:36:36

9

鋼軌3.

class Transaction < ActiveRecord::Base 
    validates_presence_of :date 
    validates_presence_of :name 

    validates_numericality_of :charge, :unless => proc{|obj| obj.charge.blank?} 
    validates_numericality_of :payment, :unless => proc{|obj| obj.payment.blank?} 


    validate :charge_xor_payment 

    private 

    def charge_xor_payment 
     if !(charge.blank?^payment.blank?) 
     errors[:base] << "Specify a charge or a payment, not both" 
     end 
    end 
end 
2
validate :father_or_mother 

#Father姓或母姓例強制

def father_or_mother 
     if father_last_name == "Last Name" or father_last_name.blank? 
      errors.add(:father_last_name, "cant blank") 
      errors.add(:mother_last_name, "cant blank") 
     end 
end 

試試上面的簡單例子。

7
class Transaction < ActiveRecord::Base 
    validates_presence_of :date 
    validates_presence_of :name 

    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, payment].compact.count != 1 
     errors.add(:base, "Specify a charge or a payment, not both") 
     end 
    end 

end 

,你甚至可以用3個或多個值做到這一點:

if [month_day, week_day, hour].compact.count != 1 
31

我認爲這是Rails的更地道3+:

如:用於驗證的user_nameemail一個是目前:

validates :user_name, presence: true, unless: ->(user){user.email.present?} 
validates :email, presence: true, unless: ->(user){user.user_name.present?} 
+18

這不處理「不是兩個」標準 – 2014-06-03 01:22:27

0

我把我的答案在下面這個問題。在這個例子中:description:keywords是字段,其中這一個不能爲空:

validate :some_was_present 

    belongs_to :seo_customable, polymorphic: true 

    def some_was_present 
    desc = description.blank? 
    errors.add(desc ? :description : :keywords, t('errors.messages.blank')) if desc && keywords.blank? 
    end