why not ben

ben tucker's virtual life. work, doings, incoming.

April 7, 2009 at 2:37pm
home

accepts_nested_attributes_for / fields_for / attr_accessible wrangling

I figured it was ripe time I figured out the new nested model forms in Rails 2.3.  After a bit of wrestling with the various pieces I got it working and figured I should share with a Google a few key pieces which would have saved me a lot of time had I found them documented when I was searching.

In this particular case I was nesting a has_one relationship, here are the relevant bits of what works:

class User < ActiveRecord::Base
   has_one :profile
   accepts_nested_attributes_for :profile
   attr_accessible :name, :profile_attributes
end 

class UsersController < ApplicationController
  def new
    @user = User.new
    @user.build_profile
  end

 def create
     @user = User.new(params[:user])
     if @user.save
       ...         
     end
  end
end

users/new.html.erb:

 <% form_for @user do |f| %>
    <%= f.text_field :name %>
    <% f.fields_for :profile do |pf| %>
      <%= f.text_field :age
    <% end %>
 <% end %>

The tricky bits were mostly figuring out where to use profile & where to use profile_attributes. The call to @user.build_profile is critical as otherwise fields_for will throw an error. Also it’s critical that attr_accessible include profile_attributes (rather than just profile).

Notes

  1. bentucker posted this