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?
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.
class ProductsController < ApplicationController
@product = Product.new
@details = Detail.new
@product = Product.new(params[:product])
@details = Detail.new(params[:details])
@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
@product = Product.find(params[:id])
On May 24, 11:24 am, Jerome D. [email protected]