我想验证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中执行此操作的正确方法是什么?
答案 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