Ruby on rails Rails 3:如何验证A<;B其中A和B都是模型属性?

Ruby on rails Rails 3:如何验证A<;B其中A和B都是模型属性?,ruby-on-rails,validation,ruby-on-rails-3,Ruby On Rails,Validation,Ruby On Rails 3,我想验证客户价格>=我的价格。我尝试了以下方法: class Product < ActiveRecord::Base attr_accessor :my_price validates_numericality_of :customer_price, :greater_than_or_equal_to => my_price ... end 在Rails 3中执行此操作的正确方法是什么?您需要执行特定的验证: validate :more_than_my_price

我想验证
客户价格>=我的价格
。我尝试了以下方法:

class Product < ActiveRecord::Base
  attr_accessor :my_price
  validates_numericality_of :customer_price, :greater_than_or_equal_to => my_price
  ...
end

在Rails 3中执行此操作的正确方法是什么?

您需要执行特定的验证:

validate :more_than_my_price

def more_than_my_price
  if self.customer_price >= self.my_price
    errors.add(:customer_price, "Can't be more than my price")
  end
end

创建自定义验证程序:

validate :price_is_less_than_total

# other model methods

private

  def price_is_less_than_total
    errors.add(:price, "should be less than total") if price > total
  end

这实际上是正确的方法,但是你的信息是错误的(“应该小于总数”),我会使用“除非”,因为这里更明显(“除非价格<总额”,或者至少“如果价格>=总额”,请注意“>=”)。否则这个例子就没有意义了。@hurikhan77:谢谢,我现在已经解决了这个问题。@RyanBigg如果没有提供price或total,这段代码将失败。不需要自定义验证器,请看,也许您只需要一个冒号就可以使我的价格成为一个符号?可能是
validate :price_is_less_than_total

# other model methods

private

  def price_is_less_than_total
    errors.add(:price, "should be less than total") if price > total
  end