views:

227

answers:

2

I have followed Ryan Bates tutorial on nested models. Several of my nested models have dates associated with them. In my migrations, they are actually the type "Date."

Some things I have tried and problems I've run into

  1. date_select - can handle the form object prefix, but not nested models attributes
  2. select_year - doesn't work with form object
  3. a regular select populated with the year by using (Time.now.year - 100)..(Time.now.year) and overriding the attr accessor start_date and end_date to take the value in the select to form a date and passing that back. works on create only, not on update
  4. changing the data type of the field to string and using a regular select populated with the year by using using (Time.now.year - 100)..(Time.now.year) works, but on edit, it won't repopulate the select with the current information

Any ideas or hints would be helpful.

Edit: before_save seems to be more promising but for some reason, the value is nil coming into before save but is visible in the log dump.

Edit 2: Interestingly, this only seems to be a problem on 'update', not on 'create'.

+1  A: 

I'd seriously hope that this works for date_select as well:

http://jeffperrin.com/2009/06/04/rails-nested-forms-and-collection_select/

Jeff Perrin
Unfortunately it doesn't. You have to apply a bit of a hack to make it work. <% date_select('attorney[memberships_attributes][NEW_RECORD]', "enddate", :start_year => 2015, :end_year => 1900, :order => [:month, :day, :year], :prompt => { :day => 'Day', :month => 'Month', :year => 'Year' }) %>. The 'attorney[memberships_attributes][NEW_RECORD]' is prefixed onto the select and then uses the correct attribute. This works only if you are able to replace 'NEW_RECORD' at the time of creating the nested model, which isn't possible.
davidstites
A: 

This is the solution:

<% new_or_existing = task.new_record? ? 'new' : 'existing' %>
  <% prefix = "project[#{new_or_existing}_task_attributes][]" %>

<% fields_for prefix, task do |t| -%>
   <%= t.date_select(:start_date, :index => task.id || nil) %>
<% end -%>

Here's the explanation of why it works:

http://agilerails.wordpress.com/2009/03/11/date_select-time_select-doesnt-work-with-auto_prefix-object/

MikeH