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 ?
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.
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 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With