Rails app config.time_zone not applying when populating form fields for '/edit' view
I specified config.time_zone in my Rails app, but the retrieved times in form fields still render as the UTC (which creates problems on updates). Shouldn't this be converted to local time in the specified zone?
/config/application.rb (relevant lines only):
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 (relevant lines only:)
<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 the datetime string to create a new event, the value is saved properly (in UTC) and rendered in my views as desired (in the local time zone) where it had been rendering UTC before the config.time_zone switch (so I know the switch was made).
But when I go to edit any other attribu开发者_如何学运维te of the event, the time rendered to the form field in the /edit view is the UTC time--which means when I update the event, the time is re-saved as though the time had been re-entered and presumed local, which shifts the time by 5 hours (my local difference from UTC) as the system converts the "updated" time attribute to UTC for storage.
How can I make the localized time be rendered in my form fields?
Running Rails 3.0.5, deploying to Heroku (though the problem exists in both development and production environments)
It turns out the real problem was in the text_fields themselves.
My 'config.time_zone' setting was working just fine (without any extra methods or hacks) in my 'index' and 'show' views, and it worked in the 'edit' view, too, as long as I used a datetime_select instead of a text_field.
As this wasn't an option for me (I was using jQuery UI's DatePicker, which needs a text_field), I investigated the text_field specific problem and answered another StackOverflow question of my own on the subject.
If you're having the text_field problem, check out that question/answer.
Just use this:
<div class="field">
<%= f.label :time_start %><br />
<%= f.datetime_select :time_start, :class => "datetimefield" %>
</div>
I create a little app for this and it's works.
You can do something like this:
heroku config:add TZ=America/Chicago
That should fix your issue on Heroku.
精彩评论