当我尝试:
validates_inclusion_of :time_zone, :in => TimeZone
validates_inclusion_of :time_zone, :in => Time.zone
出现此错误:
"<class:User>": uninitialized constant User::TimeZone (NameError)
我试图让用户选择世界上任何时区,但由于我位于美国,我的选择菜单是:
<%= f.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones, {:prompt => "Select Your Time Zone *"}, {:id => "timezone"} %>
这样做的正确方法是什么?
谢谢。
答案 0 :(得分:4)
如果选择值为"(GMT-05:00) Eastern Time (US & Canada)"
的选项,则此字符串将传递给模型进行验证。您validates_inclusion_of
将使用Enum
传递的集合上运行:in
的{{3}}方法。
Timezone
和Time.zone
都不会Enum
扩展Enum
,因此他们将不返回.include?
ActiveSupport::TimeZone.us_zones
个实例将返回true / false。
如果您的选择包含validates_inclusion_of :time_zone, :in => ActiveSupport::TimeZone.us_zones
,那么您应该检查包含验证器
ActiveSupport::TimeZone.us_zones
但是由于Enum
没有返回字符串,因此可以通过一种方式获得用于比较的公共类型,即将上述validates_inclusion_of :time_zone, :in => ActiveSupport::TimeZone.us_zones.map(&:to_s)
的内容转换为字符串。
"(GMT-05:00) Eastern Time (US & Canada)"
有了这个,像true
这样的选定值应评估> ActiveSupport::TimeZone.us_zones.map(&:to_s).include?("(GMT-05:00) Eastern Time (US & Canada)")
=> true
,如下所示在控制台中没有问题。
{{1}}
答案 1 :(得分:3)
我认为这是一个更好的解决方案:
validate :time_zone_check
def time_zone_check
# I allow nil to be valid, but you can change to your likings.
if time_zone && ActiveSupport::TimeZone.new(time_zone).nil?
errors.add(:time_zone)
end
end
原因是:
Rails缓存new
使用的现有TimeZone对象。因此,使用它来查找对象不会创建额外的对象。 (ActiveSupport::TimeZone.us_zones.map(&:to_s)
肯定会)
如果您碰巧从其他地方导入time_zone(例如浏览器用户代理),您将获得TZInfo标识符,这些标识符可能不在ActiveSupport::TimeZone.all
中。相关问题如下:https://github.com/rails/rails/issues/7245
答案 2 :(得分:1)
你可以使用
ActiveSupport::TimeZone.us_zones.map(&:name)
要么
ActiveSupport::TimeZone.us_zones.map{ |tz| tz.tzinfo.name }
在选择菜单中列出时区,您可以添加上面提到的类似自定义验证。像,
validate :check_timezone
def is_proper_timezone
errors.add(:time_zone, 'invalid') unless ActiveSupport::TimeZone[time_zone]
end