# Form\_for for nested objects

**URL:** <https://www.ruby-forum.com/t/form-for-for-nested-objects/133522>\
**Category:** Rails\
**Created:** [May 24, 2007, 5:24pm UTC](https://www.ruby-forum.com/t/form-for-for-nested-objects/133522 "2007-05-24T17:24:21Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jerome\_D](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/d6d6ee/32.png) [@Jerome\_D](https://www.ruby-forum.com/u/Jerome_D)\
**Post date:** [May 24, 2007, 5:24pm UTC](https://www.ruby-forum.com/t/form-for-for-nested-objects/133522/1 "2007-05-24T17:24:21Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![Jerome\_D](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/d6d6ee/32.png) [@Jerome\_D](https://www.ruby-forum.com/u/Jerome_D)\
**Post date:** [May 24, 2007, 8:57pm UTC](https://www.ruby-forum.com/t/form-for-for-nested-objects/133522/2 "2007-05-24T20:57:03Z")

</div>

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](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. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
