256 words — 2 minutes read

Rails 2.3 and Nested Forms within Nested Routes

Last week I finally got a chance to use the new nested routes in a small rails app, managing invoices for one of our clients. Each invoice belonged to a school and both schools and invoices had an address. It seemed (and was!) the perfect oppurtunity for nesting some forms. I whipped up a sample for the schools and wow! It worked. Automagically.

Perfect. So onto the invoices. Now, logically, the invoices belong to a school, so using another bit of Rails magic I had nested the routes. This was great, as it gave me access to the school and kept everything neat and clean. But… the nested forms within the nested routes (lots of nesting going on around here, I know, but bear with me) exploded. They just refused to work.

Upon closer inspection (and after some swearing and carrying on), I noticed that the the names of the parameters were wrong. They were in fact totally different than the forms that worked… After a bit more carrying on (and on the train on the way home by now) I realized that the parent form, that is the school and the one that was working used the form_for method with a @school instance variable. The invoice form did not–it used the less “smart” version of form_for, with a route. This was the key. Switch it to

  - form_for [ @school, @invoice ] do

instead of

  - form_for @invoice, url => school_invoice_path(@school, @invoice) do

and everything works. Nested forms for all!


Jens-Christian Fischer

Maker. Musician