0

ユーザーが選択したタイムゾーンに従って、Ruby アプリケーションの各タイムスタンプを作成したいと考えています。私はRailsでRubyを初めて使用するので、その方法がわかりません。

ユーザーがタイムゾーンを選択できるようにドロップダウンリストを表示させました

<%= time_zone_select( "user", 'time_zone', ActiveSupport::TimeZone.all, :default => "Beijing")%>

タイムゾーンの選択を、使用されるすべてのタイムスタンプに反映させる方法。

4

1 に答える 1

1

before_filterinを使用するapplication_controller.rbと、このメソッドがすべてのリクエストで呼び出されるようになります。すべてのリクエストのデフォルトのタイムゾーンはによって設定されるconfig.time_zoneため、すべてのリクエストで更新する必要がありますTime.zonehttp://api.rubyonrails.org/classes/Time.htmlを見てください

before_filter :set_user_timezone

def set_user_timezone
  if current_user && current_user.time_zone.present?
    Time.zone = current_user.time_zone
  end
end

特定のタイムゾーンを使用して式を評価するには、Time.use_zone

Time.use_zone('Singapore') do
  Time.zone.parse(...) # returns a time in Singapore
end

更新:sessionタイムゾーンの保存に使用

# application_controller.rb
before_filter :set_user_timezone

def set_user_timezone
  Time.zone = session[:timezone] || 'Default timezone here'
end

# time_zone_controller.rb
def save_time_zone
  session[:timezone] = params[:timezone]
end

# routes
match 'save_time_zone' => 'time_zone#save_time_zone'

# js
$('#user_time_zone').change(function() {
  $.ajax({
    url: '/save_time_zone',
    data: { time_zone: $(this).val() }
  })
})
于 2013-02-04T09:56:32.823 に答える