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

时间:2010-12-28 09:47:56

标签: ruby-on-rails validation ruby-on-rails-3

我想验证customer_price >= my_price。我尝试了以下方法:

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

customer_price是数据库中Products表中的一列,而my_price则不是。)

结果如下:

NameError in ProductsController#index
undefined local variable or method `my_price' for #<Class:0x313b648>

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

2 个答案:

答案 0 :(得分:13)

创建自定义验证器:

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

答案 1 :(得分: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