Rails 3: How to write forms that do not align exactly with the structure of the model?

For example, if I have a simple model with a time attribute called start_time , then the direct form code will be ...

 <%= form_for newObj do |f| %> <%= render 'shared/error_messages', :object => f.object %> <div class="field"> <%= f.label :start_time %><br /> <%= f.text_field :start_time %> </div> <div class="actions"> <%= f.submit "Submit" %> </div> <% end %> 

But I would like to have two text fields: one for the date component of the time object and one for the time component of the time object.

  • How would I structure the form code?
  • In the controller, how can I organize the sending of data to the form? Do I want to separate the two components of a time object?

Thank you very much for your wisdom!

+4
source share
3 answers

I think this is probably not a direct answer to your question, but could be a good starting point:

There is a Rails select_datetime that generates drop-down menus for date and time entries (rather than a text field). See Documentation: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-select_datetime

Ryan Bates made a couple of related railscast (links to asciicasts, should contain a link to the original video):

+2
source

We can use the virtual attribute here

 class YourModel < AR::Base def start_time_ar=ar start_time = DateTime.parse(ar.join(" ")) end end 

so in your opinion:

 <%= form_for newObj do |f| %> <%= render 'shared/error_messages', :object => f.object %> <div class="field"> <%= f.label "Date" %> <%= text_field_tag "#{f.object_name}[start_time_ar][]" %><br /> <%= f.label "Time" %> <%= text_field_tag "#{f.object_name}[start_time_ar][]" %> </div> <div class="actions"> <%= f.submit "Submit" %> </div> <% end %> 
+1
source

I think using a calendar or datetime_select helper is a good way, as it will fix some formatting problems that may occur with inputs (date formats are not standardized around the world, using AM / PM or 24H, etc.).

And by breaking it, you can do most of the work automatically. Say, for example, that you have your own attribute :start_time , then you create a field for start_time(1i) for the year, start_time(2i) for the month, start_time(3i) for the day, etc., And when passing to the ActiveRecord model it will put it automatically in datetime.

0
source

All Articles