javascript - Rails time_zone_select 使用 "official"时区值

标签 javascript ruby-on-rails

我的观点(哈姆):

= 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修改allname (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/

相关文章:

Javascript:如何顺序运行慢速函数?

javascript - Ruby on Rails - 无法使用 Java 脚本将第二个应用程序作为弹出窗口打开

javascript - Rails 6 在 Rails View 中使用 Webpacker javascript 函数

sql - 如何使用 IN 查询匹配的电子邮件?

javascript - Jquery Ajax Html 响应

javascript - 在 JS 中拆分 Sprite Sheets/Chip Sets 的高性能方法是什么?

javascript - 按键对数组进行分组,并在每次迭代中创建相关键的数组

javascript - 如何模拟 jquery 就绪函数

javascript - 令人困惑的 "instanceof "结果

ruby-on-rails - 在 Heroku+localhost 上调度 Rails 任务