ActiveSupport::TimeZone; 功能:用户自行选择时区。

TimeZone类作为一个包装器,服务一个TZinfo::Timezone 实例。

 

用途:

134个时区的检索。

使用简化的英文单词来取回和显示时区:如"Beijing" => "Asia/Shanghai"。

惰性加载TZInfo::Timezone实例。

创建ActiveSupport::TimeWithZone实例,通过parse , local, at, now方法

 

设置:

application.rb:

class Application < Rails::Application

  config.time_zone = 'Beijing'

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方法。 


 

 

创建根据用户的配置,来切换时区:

  1. 给User新增一列, time_zone: string (Model)
  2. 一个操作选择timeZone的功能和界面。(routes, view, controller)
  3.  每次登陆后,根据user的time_zone来设置时区。(controller)

第二步详解:

  1. 设置routes :  resource :user
  2. rails g controller users 设置edit, update方法
  3. add edit.html.erb 新增一个form:

<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

 

posted @ 2018-07-26 09:47  Mr-chen  阅读(624)  评论(0编辑  收藏  举报