How to manage one to many within application


#1

Hi,

I have an application with a customer model, and an address model. A 

customer has a one to many relationship with an address. I currently
have an add new customer page, that incorporates an “add address”
button, which places a helper form within a div using the link_to_remote
function. I can click the add address button multiple times, and it will
add multiple address inputs to my page. I am currently storing my
customer object within a session and each time the user presses “add
address” I add an address to the customer model, and then loop through
the number of addresses my customer has and display the add address form
that many times.

My question is, how do i store this customer address information, so
that i do not loose it between clicks. Does my “add address” button have
to post the entire form and save it to the session. And if so how do I
distinguish the different addresses? Does it post it in some sort of
array?

I cannot find any examples on the web on how to do this properly, but if
you know of any please share them.

Here is my code for this so far.

_address_form

<% session[:customer].addresses.each do %>
Address Title

<%= text_field ‘address’, ‘name’ %>

Email

<%= text_field ‘address’, ‘address’ %>


<%end%>

<label for="customer_company_name">Company name</label><br>
<%= text_field 'customer', 'name'  %> <br>
<label for="customer_email">Email</label><br/>
<%= text_field 'customer', 'email'  %> <br>

#customer_new
<% @page_title = “New Customer”%>

<%= link_to 'Back', :action => 'customer_list' %>
<%= start_form_tag :action => 'customer_create' %> <%= render :partial => 'customer_form' %>
<%= link_to_remote ("Add Address", :complete => "new Effect.Highlight('mydiv')", :update => "mydiv", :url => {:action => :_address_form}) %> <%= submit_tag "Create" %> <%= end_form_tag %>
<%= link_to 'Back', :action => 'customer_list' %><%= session[:test]%>
#end customer new

#Controller
def customer_new
@tax_groups = TaxGroup.find(:all)
@states = State.find(:all)
@countries = Country.find(:all)
@terms = Term.find(:all)
@states = State.find(:all)
@countries = Country.find(:all)
@customer = Customer.new
session[:customer] = @customer
end

def customer_create
@tax_groups = TaxGroup.find(:all)
@states = State.find(:all)
@countries = Country.find(:all)
@terms = Term.find(:all)
@states = State.find(:all)
@countries = Country.find(:all)
@customer = Customer.new(params[:customer])
@customer.address.push(params[:address])

if @customer.save
  flash[:notice] = 'Customer was successfully created.'
  redirect_to :action => 'customer_list'
else
  render :action => 'customer_new'
end

@tax_groups = TaxGroup.find(:all)
@terms = Term.find(:all)

end

def _address_form
@states = State.find(:all)
@countries = Country.find(:all)
session[:customer].save
address = Address.new
session[:customer].addresses.push(address)
@customer = session[:customer]
render(:layout => false)
end

Thanks for the help!