Displaying multiple form fields for Nested Models
Posted by Daniel on 06/21/2009accepts_nested_attributes_for
Rails 2.3 brought around the ability to seamlessly nest models in forms. This works wonderfully, and saves a bunch of time, but what if you want to have multiple instances of said nested models? It is easier than you would think. Consider the following:
Models:end
end
Order Controller:
end
The form view:
A look at the generated HTML:
Great, but what if I want the deliveries dynamically?
To my knowledge, there isn't an easy way to add nested attribute fields in a manner other than handling the form fields through javascript. This seems difficult. Instead of choosing to do this, I've decided to build the form using Rails, then hiding and then showing the the form fields dynamically. Consider the following changes to the code:
The javascript, written using jQuery:$documentreadyfunction
//hide all of the delivery fields
$'.deliveries'hide;
//show the first delivery
$'.deliveries:first'show;
//find any form elements that have errors, and show their delivery parent
$'.fieldWithErrors'parents".deliveries"show;
//add a link to add deliveries
$'#delivery'append'<a href="javascript: void(0)" id="addDelivery">Add Deliveries</a>';
//start monitoring the link
$'#addDelivery'clickfunction
//if there are delivery fields hidden, show the first one
if $'.deliveries:hidden'length > 0
$'.deliveries:hidden:first'slideDown;
;
//if there are no more hidden delivery fields, remove the last link
if $'.deliveries:hidden'length < 1
$'#addDelivery'remove;
Find the demo app here: http://github.com/danielwestendorf/nested_attributes_demo/tree/master

Hi! This post can be considered as an easy way to add fields dynamically (with jQuery): http://railsforum.com/viewtopic.php?id=28447
06/29/2009