Rails 3: How to verify that A <B, where A and B are both attributes of the model?

I would like to confirm 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, but my_price is not.)

Here is the result:

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

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

+7
source share
2 answers

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 
+13
source

You need to perform a specific check:

 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 
+3
source

All Articles