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?
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".
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.
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.
try adding .keys
?
validates :time_zone,
inclusion: {
in: ActiveSupport::TimeZone.zones_map.keys
}
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With