Rails forms for has_many relations

This is pretty cool. Say you have a model with a has_many relation, and you want to edit the model and all it’s children on one page. Rails can take care of all of this, automatically, with the standard controller. You just need this in your parent model:

class User < ActiveRecord::Base
  has_many :posts
  accepts_nested_attributes_for :posts
end

And you need a form like this:

<% form_for(@user) do |f| %>
  <%= f.label_for :blog_name %>
  <%= f.text_field :blog_name %>
 
  <% f.fields_for :posts do |p| %>
    <%= p.label_for :title %>
    <%= p.text_field :title %>
    ...
  <% end %>
 
  <%= f.submit %>
<% end %>

And that’s it! You can use all the craziness that the form helpers do (grouping radio buttons, converting to values booleans, etc) and it all works out.

It’s exciting. I feel like I’m finally getting into the really good stuff with Rails.

Tags: , ,

Leave a Reply