rails validate in model that value is inside array[2] - ruby-on-rails

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

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 }

[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]

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

Related

How do I validate the length of a title in a rails app?

I'm learning Ruby on Rails right now and one of the exercises that I am trying to figure out is how to validate the title such that it has more than 10 characters. The hint says to use the :length method(?) in ruby.
So far I've tried:
validates :title.length, numericality: {greater_than_or_equal_to: 10}
and
validates :title, length: {greater_than_or_equal_to: 10}
both of which has given me errors.
What should I do here?
Another quick question, what is the difference when the colon(:) is on the left and right? for the length, it's on the left (:length), but for numericality, it's on the right (numericality:) I'm thinking if it's on the left it's a variable, and if it's on the right it's a method. Not sure if that's a good way to think of it.
Try:
validates :title, length: {minimum: 10}
To your second question:
key: value
is a hash syntax, which means the same as
:key => value
I'm not sure where you're being told to do it that way. The documentation is pretty specific:
validates :title, length: { minimum: 10 }

How to validate price in input?

I have an input (it's text input) where users can set up the price.
The problem is, that users can sometimes set up the price like this:
9
9.99
9,99
$9.99
What's the best way to validate this input? I am running the app on Heroku (= PostgreSQL database), the data type column is decimal.
Rails 4 complains about using $ and ^, so use:
validates :price, :presence => true,
:format => { :with => /\A(\$)?(\d+)(\.|,)?\d{0,2}?\z/ }
Just trying to save people time ;-)
Try something like below. It matches all you examples.
validates :price, :presence => true,
:format => { :with => /^(\$)?(\d+)(\.|,)?\d{0,2}?$/ }

Ruby ActiveRecord: validate format of an integer field

I'm trying to validate the format of a field in an ActiveRecord. I want this field to either be empty, or contain a sequence of digits only (it is containing an optional port number for a database connection). I'm currently trying this:
validates_format_of :port, with: /\A[0-9]*\Z/, message: 'Only numbers allowed'
but without luck. I've found that adding a required number by using for example {1, 6} sort of works, but makes the field mandatory.
Any advice?
Many thanks in advance,
Joseph.
If you're looking to validate so that only numbers are allowed, then you should be able to use this:
validates :port, :numericality => {:only_integer => true}
You may want to try to validate the numericality of the field, like so:
validates_numericality_of :port, :only_integer => true
:only_integer will ensure that the value entered for :port is an integer.
You can also just add allow_blank: true
You can use this syntax as well
validates numericality: :only_integer

Rails 3: Validate IP String

In Rails 3, is there a built in method for seeing if a string is a valid IP address?
If not, what is the easiest way to validate?
Just wanted to add that instead of writing your own pattern you can use the build in one Resolv::IPv4::Regex
require 'resolv'
validates :gateway, :presence => true, :uniqueness => true,
:format => { :with => Resolv::IPv4::Regex }
The Rails way to validate with ActiveRecord in Rails 3 is:
#ip_regex = /^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/
validates :gateway,
:presence => true,
:uniqueness => true,
:format => { :with => #ip_regex }
Good resource here: Wayback Archive - Email validation in Ruby On Rails 3 or Active model without regexp
You can also just call standard's library IPAddr.new that will parse subnets, IPV6 and other cool things: (IPAddr) and return nil if the format was wrong.
Just do:
valid = !(IPAddr.new('192.168.2.0/24') rescue nil).nil?
#=> true
valid = !(IPAddr.new('192.168.2.256') rescue nil).nil?
#=> false
You can use Resolv::IPv4::Regex as Jack mentioned below if you don't need to accept subnets.
If you need to accept it, activemodel-ipaddr_validator gem may help you. (disclaimer: I'm the author of the gem)
validates :your_attr, ipaddr: true
i dont know about RoR a lot, but if you dont find any built in method for validation of IP Address.
Try on this regular expression :
"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$"
to validate the IP Address.
I recently used it in one module so had it on desktop.
You should use a Regular Expression
Here is one that does what you want:
/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.
([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/.match("#{#systemIP}")
You can also use Regexy::Web::IPv4 which can match ip addresses with port numbers too.

Rails: how do I validate that something is a boolean?

Does rails have a validator like validates_numericality_of for boolean or do I need to roll my own?
Since Rails 3, you can do:
validates :field, inclusion: { in: [ true, false ] }
I believe for a boolean field you will need to do something like:
validates_inclusion_of :field_name, :in => [true, false]
From an older version of the API: "This is due to the way Object#blank? handles boolean values. false.blank? # => true"
I'm not sure if this will still be fine for Rails 3 though, hope that helped!
When I apply this, I get:
Warning from shoulda-matchers:
You are using validate_inclusion_of to assert that a boolean column
allows boolean values and disallows non-boolean ones. Be aware that it
is not possible to fully test this, as boolean columns will
automatically convert non-boolean values to boolean ones. Hence, you
should consider removing this test.
You can use the shorter version:
validates :field, inclusion: [true, false]
Extra thought. When dealing with enums, I like to use a constant too:
KINDS = %w(opening appointment).freeze
enum kind: KINDS
validates :kind, inclusion: KINDS
Answer according to Rails Docs 5.2.3
This helper (presence) validates that the specified attributes are not empty. It uses the blank? method to check if the value is either nil or a blank string, that is, a string that is either empty or consists of whitespace.
Since false.blank? is true, if you want to validate the presence of a boolean field you should use one of the following validations:
validates :boolean_field_name, inclusion: { in: [true, false] }

Resources