Is there a way to call a method on the data loaded into a form input in Rails? (Specifically a text_field)
I'm using Rails 3.0.5, and for the reasons specified in this question, I need to call a utc_to_local method on the text_field input for a datetime.
I've tried calling the method in various ways directly in the view (as a starting point), but I can't seem to find the magic mix (haven't called a method on a form field before).
/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" %><b开发者_C百科r />
<%= f.text_field :time_start, :class => "datetimefield" %>
</div>
To answer straight:
<%= f.text_field :time_start, :value => f.object.time_start.try(:method_name) :class => "datetimefield" %>
But... why don't you use in_time_zone
?
Time.now.in_time_zone("Eastern Time (US & Canada)")
Which would lead to the creation of an Application Helper:
def time_zoned(string)
return nil if string.nil?
begin
time = Time.parse(string)
rescue
return nil
end
time.in_time_zone("Eastern Time (US & Canada)")
end
And in your view:
<%= f.text_field :time_start, :value => time_zoned(f.object.time_start) %>
精彩评论