0

I'm not sure what the best way to implement this is--basically I would like to check if my :start_amount field of my model is within a range from 0 to user.amount. I'm not sure how to say 'user.amount' since it's not static like the other validations.

(for reference I did validates_numericality_of :start_amount, :allow_nil => false, :greater_than => 0

and then did this in the same model:

def validates
    self.errors.add(:start_amount, "is out of range") unless self.amount_in_allowed_range
  end

  def amount_in_allowed_range
    start_amount <= user.amount
  end

It's pretty simple so I didn't think creating another class for the validation was needed (maybe that's the only way it works?) It was working ok except when I left start_amount blank, in which case it was comparing nil <= user.amount and gave an error (which I think is weird, since it should be checking for that in the validates_numericality_of--but I guess the custom validation runs first). Then I changed it to the above with :allow_nil => false and also set it as :null => false, :default => 0 in my migrations. now it just doesn't seem to check at all? or it's permanently 0, and thus always passes validation...)

I'm really new to rails and would appreciate any help. Thanks!

1 Answer 1

4
validates_numericality_of :start_amount
validate :amount_in_allowed_range

def amount_in_allowed_range
   self.errors.add(:start_amount, "is out of range") unless start_amount <= self.user.amount
end

That should work if your current model has a belongs_to relationship to user. Note that custom validation methods are declared singular (validate instead of validates). Also, allow_nil is false by default. And I am not sure why :default => 0 was set in your routes? Did you mean migrations? Please give a bit more detail about what your setup looks like. What sort of error were you getting when nil was compared to user.amount?

Sign up to request clarification or add additional context in comments.

2 Comments

Ah yes I meant migrations, not routes for :default =>0 (corrected it). When I use what you suggested there is no change--it's as if there is no custom validation. I used def validates because it seemed like that was the default custom validation name. How could you a raise a custom error without the .errors.add? The error was a NoMethodError when nil was compared to user.amount.
You are right, you need errors.add and it needed to be conditional. I edited the method to reflect it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.