Rails 3: How to validate that A < B where A and B are both model attributes?

穿精又带淫゛_ 提交于 2020-01-14 08:01:06

问题


I would like to validate that customer_price >= my_price. I tried the following:

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

(customer_price is a column in the Products table in the database, while my_price isn't.)

Here is the result:

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

What is the right way to do this in Rails 3 ?


回答1:


Create a custom validator:

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



回答2:


You need do a specific validate :

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


来源:https://stackoverflow.com/questions/4545102/rails-3-how-to-validate-that-a-b-where-a-and-b-are-both-model-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!