TimeZone类做为一个包装器,服务一个TZinfo::Timezone 实例。html
用途:app
134个时区的检索。ui
使用简化的英文单词来取回和显示时区:如"Beijing" => "Asia/Shanghai"。url
惰性加载TZInfo::Timezone实例。spa
建立ActiveSupport::TimeWithZone实例,经过parse , local, at, now方法设计
设置:orm
application.rb:htm
class Application < Rails::Applicationstring
config.time_zone = 'Beijing'it
end
Time.zone 输出一个实例变量
Time.zone.name 输出 “Beijing”
Time.zone.now 输出一个TimeWithZone实例 Thu, 26 Jul 2018 09:27:24 CST +08:00
✅,TimeWithZone实例 使用Ruby Time实例的相同的API方法。
建立根据用户的配置,来切换时区:
第二步详解:
<div class="form-group">
<%= f.label :time_zone %>
<%= f.time_zone_select :time_zone, /Beijing/ %> ⚠️:time_zone_select方法是formbuilder方法。
</div>
最后一步:
在application控制器中:
before_action :set_timezone
def set_timezone
if current_user && current_user.time_zone
Time.zone = current_user.time_zone
end
end
关于设置resource :user
解释:不加S,生成不带id的url。没有index_action。
设计的缘由:前台用户更改的是自身的内容,无需id来判断本身和他人的区别。同时网址也不会带id,隐秘性好(无需特地设置网址乱数)。
new_user GET /user/new(.:format) users#new
edit_user GET /user/edit(.:format) users#edit
user GET /user(.:format) users#show
PATCH/PUT /user(.:format) users#update
DELETE /user(.:format) users#destroy
POST /user(.:format) users#create