I have a model, Offer, that belongs to a User. Users have an attribute :prepaid_amount that represents an amount of money, and :bid_total, which is the sum of all money bid on items, multiplied by the quantities of each bid. So, a User with two bids, one with quantity => 3 and amount => 10, and another with quantity => 2 and amount => 3, has a bid_total of 36.
If the prepaid_amount is greater than this value, everything is fine. Assume the prepaid_amount is 40.
If I want to validate a new bid from the user, of quantity => 1, then the amount of the bid can be any integer above 0, and up to 4. If it’s zero, then 1*0, and the validation should fail because a bid must be greater than zero. If the amount is (say) 5, the bid should not validate, because 36 + 1*5 = 41, which is greater that the prepaid_amount.
How do I create such a validation in Rails 3 in the Offer model? Here’s what I have, which doesn’t work :
class Offer < ActiveRecord::Base
belongs_to :user
validates :user_id, :presence => true, :numericality => true do
validates :qty, :presence => {:if => Proc.new { |offer| (offer.user.prepaid_amount-offer.user.bid_total)/offer.amount >= offer.qty} }
end
end
Have you considered using a custom validation method?
One might argue that this is not the perfect rails way of validation but if your validation is so complex you might consider isolating it in its own method.