0

This question similar with this one, but those answers don't work for me(May be they are deprecated). I don't want to reopen old question by bounty, because I have a little different arguments. In my case i have an array like this allowed_values = [99.50..200] and I tried with:

class Thing < ActiveRecord::Base
   validates :price, :inclusion=> { :in => allowed_values }

It does not work. I have tried with so many ways by examples validation here. I have little experience on coding rails. So please, help to find solution.

More info:

       ruby version: ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-linux]
       rails version: Rails 4.1.5
1
  • Does the price datatype is Float/Integer? If it is String it won't work. Commented Oct 3, 2016 at 13:46

3 Answers 3

1

The problem must be with the way you pass the allowed_values array.

You can go with this:

validates :price, inclusion: { in: (99.50..200) }

Or, with a constant:

ALLOWED_VALUES = (99.50..200).freeze
validates :price, inclusion: { in: ALLOWED_VALUES }
Sign up to request clarification or add additional context in comments.

4 Comments

it does not work. does it depend on version of ruby or rails ?!
@Ulug'bekRo'zimboyev which version do you use? In which way is this not working? What errors do you get?
@Ulug'bekRo'zimboyev my question is still topical: which errors do you get?
it gives no error, why i say does not work, because if i set price=12, it says the model is valid. that's why I said it doesn't work
1

[99.50..200] is an array that contains a single element: the range (99.50..200).

You are testing whether the value is in the list of objects in the array, but what you probably want is to test whether it is in the range.

So define:

allowed_values = (99.50..200)

instead of:

allowed_values = [99.50..200]

Comments

1

I have found a solution: How to implement min/max validator in Rails 3?

validates :price, :inclusion=> { :in => allowed_values }

does not work, it seems, validation style was changed after 3 version of rails. And I tried with:

validates_inclusion_of :number, :in => min_price..max_price

This solution has no valid case if min_price=10.5 and max_price=11

My solution is:

validates :price, :numericality => { :greater_than_or_equal_to => min_price, :less_than_or_equal_to => :max_price }

I don't know ruby(and rails) deeply and I am not right some cases. but this solution is working

Comments

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.