2010-01-25 52 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 
相关问题