Topic: Adding and removing dynamic rows to a form


I've created an application where each 'event' has many 'event_days'.
When creating a new event the user is given a form, with one event_day row to complete.  beneath that is a button 'add new day'.  If they click this a further row appears, with the same form fields, allowing the user to add a further day.  They can add as many days as they like, and when they click 'save' the event and all its event_days are written to the database.

The link that adds a day calls the following rjs:


page.insert_html :bottom, "event_days", :partial => 'event_days/list_item'

and the partial it adds looks like this:

    <%= text_field_tag "event_days[][day]"%>
    <%= select_tag "event_days[][start_at]", time_options %>
    <%= select_tag "event_days[][finish_at]", time_options %>
    <%= link_to_remote "remove day", :url => { :action => 'remove_event_day' } %>

Where I'm coming unstuck is on this 'remove_event_day' link.  Since I'm not uniquely identifying the rows as I add them, I can't get a handle on the one the 'remove' link corresponds to... or can I?

Any help would be greatly appreciated.

Re: Adding and removing dynamic rows to a form

Ah, I found just the tutorial I was after...


Re: Adding and removing dynamic rows to a form

However, I'm trying to use a different form helper than just a simple text field.  Since it's a date I've opted to use CalendarDateSelect (

When I try to integrate it into my form with:

<% fields_for "event_days[#{index}]", event_day do |f| %>
  <li id="event_day_<%= index %>">
    <%= f.calendar_date_select :day %>
    <%= f.text_field :start_at, :size => 10 %>
    <%= f.text_field :finish_at, :size => 10 %>
    <%= link_to_remote 'remove', :url => { :action => 'remove_event_day', :index => index } %>
<% end %>

I get the following error:
NoMethodError in Events#new
Showing app/views/events/_event_day_fields.rhtml where line #5 raised:
(eval):1:in `calendar_date_select': You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]

I'm sure it's to do with the way the form id/name is generated since if I change line 2 of the first snippet of code to:
<% fields_for "event_days_#{index}", event_day do |f| %>

The page displays and calls back data into this field correctly.

However, this now means we're not passing a hash, hence Ryan's tutorial's ( create action no longer works...

def create
  @event =[:event])
  params[:event_days].each_value { |event_day| }
    redirect_to :action => 'index'
    render :action => 'new'

Am I going about this the wrong way?  Or is it that CalendarDateSelect needs to be tweaked a bit?  Any help would be greatly appreciated!

Last edited by idrysdale (2007-09-09 18:24:53)