Form_for for nested objects

Hi,

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 http://www.pragmaticprogrammer.com/titles/rails2 for more book

information.
#—
class ProductsController < ApplicationController

def new
@product = Product.new
@details = Detail.new
end

def create
@product = Product.new(params[:product])
@details = Detail.new(params[:details])

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

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

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

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