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?
Unlike regular CRUD interfaces, there’s not a prescribed “Rails Way” to do multi-step forms. This, plus the fact that multi-step forms are often inherently complicated, can make them a challenge.
Adding related models means establishing meaningful relationships between them, which then affect how information gets relayed through your application’s controllers, and how it is captured and presented back to users through views. In this tutorial, you will build on an existing Rails application that offers users facts about sharks.
To summarize the solution to the easy type of multi step form: For each step of your form, create a controller that corresponds to the Active Record model that’s associated with that step. Again, this solution only works if your form steps and your Active Record models have a one-to-one relationship.
For example, let’s say that you have a form with two steps. In the first step you collect information about a user’s vehicle. The corresponding model to this first step is Vehicle.
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
class Company < ActiveRecord::Base
has_many :people, :dependent => :destroy
accepts_nested_attributes_for :people, :allow_destroy => true
end
class person < ActiveRecord::Base
belongs_to :company
end
def new
@company = Company.new
3.times { person = @company.people.build }
end
<% 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 %>
<p>
<%= f.label :name, "Person" %>
<%= f.text_field :name %>
<%= f.check_box :_destroy %>
<%= f.label :_destroy, "Remove" %>
</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With