0

I am trying to filter and returning only the time zones from a specific country.

At now, i tried the without success:

# wrong code - i used Brazil only for tests.

validates_inclusion_of :time_zone, in: ActiveSupport::TimeZone.zones_map(&:name)    
= f.input :time_zone, collection: TZInfo::Timezone.all.find_all{ |z| z.name =~ /Brazil/ }

# Return: [#<TZInfo::TimezoneProxy: Brazil/Acre>, #<TZInfo::TimezoneProxy: Brazil/DeNoronha>, #<TZInfo::TimezoneProxy: Brazil/East>, #<TZInfo::TimezoneProxy: Brazil/West>]

It will fail at validation, because the differences TimeZone types, then i tried this conversion How to convert TZInfo to Rails Timezone but this doesn't work too, there are differences at MAPPING vectors.

Community
  • 1
  • 1
Ricardo
  • 667
  • 9
  • 25

1 Answers1

1

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
Nidhi
  • 340
  • 2
  • 10