Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 440
Misha Moroshko Avatar asked Dec 28 '10 09:12

Misha Moroshko


People also ask

What is the difference between validate and validates in Rails?

So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.

How does validate work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.

What is Active Record in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


1 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
like image 56
Ryan Bigg Avatar answered Sep 28 '22 03:09

Ryan Bigg