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

Mis*_*hko 7 validation ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)

(customer_priceProducts数据库中表中的一列,而my_price不是.)

结果如下:

NameError in ProductsController#index
undefined local variable or method `my_price' for #<Class:0x313b648>
Run Code Online (Sandbox Code Playgroud)

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

Rya*_*igg 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
Run Code Online (Sandbox Code Playgroud)

  • 无需自定义验证器,请参阅http://stackoverflow.com/questions/4416278/how-to-implement-min-max-validator-in-rails-3 (2认同)