Form_for for nested objects


I have the following data model:

  • Person (name, …)
  • Address (street, city)
  • Person has_ony Address

I would like to edit the Person and its Address in one single form.
Using form_for, I can add the person fields. Using fields_for, I could
have the Address also, but it’s not nested here (aka
person[address[street]]. So the question is how to “prefix” the
field_for to include the Address hash into the Person hash?

Thank you!

It doesn’t appear that you can do that. But, the solution is to take
care of the association in the create method.

See this example notice the use of a database transaction to properly
handle the rollback:

Excerpted from “Agile Web D. with Rails, 2nd Ed.”

We make no guarantees that this code is fit for any purpose.

Visit for more book

class ProductsController < ApplicationController

def new
@product =
@details =

def create
@product =[:product])
@details =[:details])

Product.transaction do
  @details.product = @product!!
  redirect_to :action => :show, :id => @product

rescue ActiveRecord::RecordInvalid => e
@details.valid? # force checking of errors even if products
render :action => :new

def show
@product = Product.find(params[:id])

On May 24, 11:24 am, Jerome D. [email protected]