[英]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
。
Timezone
和Time.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
原因是:
Rails緩存現有的TimeZone對象,這些對象是new
用的。 因此,使用它來查找對象不會創建額外的對象。 ( ActiveSupport::TimeZone.us_zones.map(&:to_s)
肯定會)
如果您碰巧從其他地方導入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.