Jabberwocky

snicker-snack!

Nested Forms in Rails 2.3

| Comments

I’ve had the opportunity to use the new and improved nested forms in Rails. When you have a has_many relationship, you can add, modify or delete the many instances corresponding to your one instance. Well, they work. I can even go one further: they work when you have nested forms in nested forms. I’ve used things like:

1
2
3
4
5
6
7
8
9
<% form_for :library, :url => library_path(@library), :html => {:method => :put} do |f| %>
  <%= f.text_field :name %>
  <% f.fields_for :books do |b| %>
    <%= b.text_field :author %>
    <% b.fields_for :chapters do |c| %>
       <%= c.text_field :title %>
    <% end %>
  <% end %>
<% end %>

You have to have initialized the objects in question in your controller (using build), or they need to exist already to appear in the form.

But i was actually surprised that it just worked, without further ado !  Very decent code in that form_helper, congrats to the developers.

One thing i find slightly less well done, is that when you want to step outside of the Rails magic to make some slightly more involved markup, you cannot retrieve the index the fields_for generates. I worked around this by doing something ugly but effective in the view:

1
2
3
4
5
<% i  = 0 %>
<% f.fields_for :books do |b| %> >
  ...
  <% i  = 1 %>
<% end %>

And using i as the index in the markup.

Comments