views:

90

answers:

1

I have a model that has an arbitrary number of children entities. For simplicity lets call the entities Orders and Items. I would like to have a create Orders form where I input the order information, as well as add as many items as I want. If I click the "Add another item" button, a new set of form elements will be added to input the new data, amounts, etc..

I could hack this out in pure javascript, but I'm pretty sure there has to be a more magical, railsish way to do it, maybe with a partial view or something. I'm just a little too new to rails to know what it is.

What is the best way to dynamically add the new form elements, and then to access them in the create controller?

+2  A: 

Can't beat this Railscasts.com tutorial provided by Ryan Bates.

Episode 196: Nested Model Form, pt. 1

Here's an example that works with just a single level of nesting

Models

models/company.rb

class Company < ActiveRecord::Base
  has_many :people, :dependent => :destroy
  accepts_nested_attributes_for :people, :allow_destroy => true
end

models/person.rb

class person < ActiveRecord::Base
  belongs_to :company
end

Controllers

companies_controller.rb

def new
  @company = Company.new
  3.times { person = @survey.people.build }
end

Views

views/companies/_form.html.erb

<% form_for @company do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>

  <% f.fields_for :people do |builder| %>
    <%= render "people_fields", :f => builder %>
  <% end %>

  <p><%= f.submit "Submit" %></p>
<% end %>

views/companies/_people_fields.html.erb

<p>
  <%= f.label :name, "Person" %>
  <%= f.text_field :name %>
  <%= f.check_box :_destroy %>
  <%= f.label :_destroy, "Remove" %>
</p>
macek
No, you really can't
CaptnCraig