How to validate inclusion of time zone?

When I try:

validates_inclusion_of :time_zone, :in => TimeZone
validates_inclusion_of :time_zone, :in => Time.zone

This error appears:

"<class:User>": uninitialized constant User::TimeZone (NameError)

I'm trying to let users select any time zone of the world but since I'm based in the U.S.A. my select menu is this:

<%= f.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones, {:prompt => "Select Your Time Zone *"}, {:id => "timezone"} %>

What's the correct way to do this?

Thank you.

Answers


If you select the option with value "(GMT-05:00) Eastern Time (US & Canada)" this string is going to be passed to the model for validation. Your validates_inclusion_of is going to run Enum's .include? method on the collection you pass with :in.

Neither Timezone and Time.zone extend Enum to my knowledge, so they will not return an Enum instance that .include? will return true/false for.

If your select consists of ActiveSupport::TimeZone.us_zones, this is what you should be checking the inclusion validator against

validates_inclusion_of :time_zone, :in => ActiveSupport::TimeZone.us_zones

But as ActiveSupport::TimeZone.us_zones doesn't return strings, one way you could get a common type for comparison is casting the above Enum's contents to strings.

validates_inclusion_of :time_zone, :in => ActiveSupport::TimeZone.us_zones.map(&:to_s)

With this, a selected value like "(GMT-05:00) Eastern Time (US & Canada)" should evaluate true, as the following does in console without trouble.

> ActiveSupport::TimeZone.us_zones.map(&:to_s).include?("(GMT-05:00) Eastern Time (US & Canada)")
=> true

Need Your Help

run an Excel Macro from Python (but an Excel process stays in memory)

python excel win32com

with the following python method, I make a call to an Excel macro. I was happy when I got that to work, however I was wondering everytime I was executing this I could see a Windows temporary/lock f...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.