繁体   English   中英

如何验证时区的包含?

[英]How to validate inclusion of time zone?

当我尝试:

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"} %>

这样做的正确方法是什么?

谢谢。

如果选择值为"(GMT-05:00) Eastern Time (US & Canada)"此字符串将传递给模型进行验证。 你的validates_inclusion_of将运行Enum.include? 你传递的集合的方法:in

TimezoneTime.zone都没有将Enum扩展到我的知识,所以他们不会返回一个Enum实例.include? 将返回true / false。

如果您的选择包含ActiveSupport::TimeZone.us_zones ,那么您应该检查包含验证器

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

我认为这是一个更好的解决方案:

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

原因是:

  1. Rails缓存现有的TimeZone对象,这些对象是new用的。 因此,使用它来查找对象不会创建额外的对象。 ActiveSupport::TimeZone.us_zones.map(&:to_s)肯定会)

  2. 如果您碰巧从其他地方导入time_zone(例如浏览器用户代理),您将获得TZInfo标识符,这些标识符可能不在ActiveSupport::TimeZone.all 相关问题在这里: https//github.com/rails/rails/issues/7245

你可以用

ActiveSupport::TimeZone.us_zones.map(&:name)ActiveSupport::TimeZone.us_zones.map{ |tz| tz.tzinfo.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM