Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 'config.time_zone' doesn't apply to datetime data loaded into a text_field. Fix?

When I use a datetime_select in my form, Rails will correctly adjust the timezone of the datetime data (as per my config.time_zone setting), and will render the properly-zoned time in the edit view of that same form.

But when I try to retrieve that same data into a text_field (for the same edit view of the same form), Rails doesn't seem to adjust for time zone.

/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>

Example: My zone's offset is -500. I enter 8:00 as the start_time in the form, 13:00 UTC is written to the database, 8:00 is rendered on the show page (thanks to config.time_zone accounting for the offset), but when I try to edit that object, the form's text_field for the start_time is loaded with 13:00 (which, if submitted unaltered, becomes 18:00 when it's stored in the database).

This is problematic, because I'm trying to use jQuery UI's DatePicker (with a TimePicker add-on), which relies on the text_field (won't work with a datetime_select).

Is there a way to make Rails apply the config.time_zone offset to text fields?

Running Rails 3.0.5, deploying to Heroku.

Apologies in advance for having asked a very similar question a few weeks ago. The information there still applies, I just have a better understanding of the problem now, so I re-asked.

like image 867
jasonmklug Avatar asked Jul 01 '11 23:07

jasonmklug


1 Answers

As I said in the question, the main problem I had was getting ActiveRecord to apply the existing 'config.time_zone' setting to text_fields.

It turns out that there's a very simple and future-proof way to make that happen: just explicitly add a :value and pull the exact same data--no extra/new methods to call! In my case, that meant:

<%= f.text_field  :time_start, :value => f.object.time_start, :class => "datetimefield" %>

This was an intermediary step to another potential solution I was going to try, and I was surprised to find that it worked all on its own (again, working with the 'config.time_zone' I'd already set in 'config/application.rb').

I've tested it, and it applies the proper DST offset when applicable as well (just as one would expect, since 'config.time_zone' is set).

like image 172
jasonmklug Avatar answered Oct 23 '22 06:10

jasonmklug