Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validates_inclusion_of no longer working the same in Rails 4.1?

The following code made sure that a time_zone chose is within the time zones in ActiveSupport::TimeZone.us_zones:

validates_inclusion_of :time_zone, in: ActiveSupport::TimeZone.zones_map(&:name)

Worked great in Rails 4.0. Just upgraded to Rails 4.1 and I'm getting this error on my index page (so just simply viewing the models):

An object with the method #include? or a proc, lambda or symbol is required, and must be supplied as the :in (or :within) option of the configuration hash

I'm guessing from that, ActiveSupport::TimeZone.zones_map(&:name) is no longer a valid value for the in property?

like image 678
at. Avatar asked Apr 09 '14 00:04

at.


People also ask

How do I validate in Ruby on Rails?

This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".

How does validation work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.

Can we save an object in the DB if its validations do not pass?

Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful. The following methods trigger validations, and will save the object to the database only if the object is valid: create.


2 Answers

try adding .keys ?

validates :time_zone, 
  inclusion: { 
    in: ActiveSupport::TimeZone.zones_map.keys 
  } 
like image 123
house9 Avatar answered Sep 19 '22 16:09

house9


In Rails 5, ActiveSupport::TimeZone.zones_map is a private method. Therefore, if you want your validation to work, I suggest the following syntax:

validates :time_zone, inclusion: { in: ActiveSupport::TimeZone.all.map(&:name) }
like image 22
kogitoja Avatar answered Sep 20 '22 16:09

kogitoja