Rails app config.time_zone is not applied when filling in the form fields for viewing "/ edit"

I specified config.time_zone in my Rails application, but the forms received in the fields are still displayed as UTC (which creates problems when updating). Shouldn't it be converted to local time in the specified zone?

/config/application.rb (only relevant lines):

module ExampleSite class Application < Rails::Application config.time_zone = 'Central Time (US & Canada)' end end 

/events/edit.html.erb(full file):

 <h1>Edit This Event</h1> <%= form_for(@event) do |f| %> <%= render 'fields', :f => f %> <div class="actions"> <%= f.submit "Update Event" %> </div> <% end %> 

/events/_fields.html.erb(only matching lines :)

 <div class="field"> <%= f.label :time_start, "Start Time" %><br /> <%= f.text_field :time_start, :class => "datetimefield" %> </div> <div class="field"> <%= f.label :time_end, "End Time (if applicable)" %><br /> <%= f.text_field :time_end, :class => "datetimefield" %> </div> 

When I enter a date and time string to create a new event, the value is stored properly (in UTC format) and rendered in my views as desired (in the local time zone), where it displayed UTC before switching config.time_zone (so I know that the switch has been made).

But when I go on to edit any other attribute of the event, the time displayed in the form field in the / edit view is UTC time - this means that when I update the event, the time restarts, as if the time were re-entered and supposedly locally, which shifts the time by 5 hours (my local difference from UTC), because the system converts the β€œupdated” time attribute to UTC for storage.

How to make localized time displayed in my form fields?

Running Rails 3.0.5, deployment in Heroku (although the problem exists in both development and production environments)

+5
timezone datetime ruby-on-rails ruby-on-rails-3 forms
source share
3 answers

It turns out that the real problem was in the text boxes themselves.

In the "index" and "show" settings, my "config.time_zone" setting worked fine (without any additional methods or hacks), and it also worked in the "edit" view if I used datetime_select instead of a text field.

As it was not for me (I used the jQuery UI DatePicker, which needs a text field), I explored the specific problem of text_field and https://stackoverflow.com/a/166269/169 .

If you have a problem with the text, check this question / answer.

+8
source share

Just use this:

  <div class="field"> <%= f.label :time_start %><br /> <%= f.datetime_select :time_start, :class => "datetimefield" %> </div> 

I create a small application for this, and it works.

+1
source share

You can do something like this:

 heroku config:add TZ=America/Chicago 

This should fix your problem on Heroku.

0
source share

All Articles