我的观点(哈姆):
= f.time_zone_select :time_zone, nil, {}, class: 'form-control'
呈现给:
...
<option value="Ljubljana">(GMT+01:00) Ljubljana</option>
<option value="Madrid">(GMT+01:00) Madrid</option>
<option value="Paris">(GMT+01:00) Paris</option>
<option value="Prague">(GMT+01:00) Prague</option>
...
创建记录时,我想设置
:time_zone
归属于用户的当前时区。有几种方法可以做到这一点,但经过研究,我发现了 gem timezone_local
或 JS 库 jstz
最常见的。无论哪种方式,所有这些开源库似乎都使用与 rails 不同的模式,例如巴黎时区定义为:
Europe/Paris
但是,Rails 中的 TimeZone 对象使用
Paris
当我想使用用户的当前时区创建记录时,这会导致不一致,因为它不匹配。我需要 rails 使用与
jstz
相同的模式反之亦然,但我不想 gsub
这里的字符串或类似的。这里最好的方法是什么?
最佳答案
您可以使用Draper修改all
和 name
(time_zone_select
使用的列表和值方法):
class TimeZoneDecorator < Draper::Decorator
decorates ActiveSupport::TimeZone
delegate_all
def self.all
TimeZoneDecorator.decorate_collection(ActiveSupport::TimeZone.all)
end
def self.us_zones
TimeZoneDecorator.decorate_collection(ActiveSupport::TimeZone.us_zones)
end
# other custom collection methods
def name
tzinfo.name # "Europe/Paris" instead of "Paris"
end
end
然后使用
model
标签中的选项:= f.time_zone_select :timezone, TimeZoneDecorator.us_zones, {include_blank: "Set from Lat/Lng", model: TimeZoneDecorator}, {class: 'form-control'}
关于javascript - Rails time_zone_select 使用 "official"时区值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41017984/