问题
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