Parent Child form using Partials

I am trying to make a simple application which consists of contacts and
their addresses.

class Contact < ActiveRecord::Base
has_many :addresses
end

class Address < ActiveRecord::Base
belongs_to :contact
end

I would like to be able to edit/add addresses from within the edit/add
of the contact. I scaffolded the contact and address objects and
modified the contacts/_form partial as follows:

<%= error_messages_for ‘contact’ %>

Name
<%= text_field 'contact', 'name' %>

<%= render :partial => 'addresses/form', :collection => @contact.addresses %>

The addresses/_form partial looks like this:


<%= error_messages_for 'address' %>

Line 1
<%= text_field 'address', 'line_1' %>

Line 2
<%= text_field 'address', 'line_2' %>

City
<%= text_field 'address', 'city' %>

State
<%= text_field 'address', 'state' %>

Zip
<%= text_field 'address', 'zip' %>

I am running into to issues with this design. 1) I’ve manually added
address objects into the table and when i go to addresses/edit/1, it
renders the two addresses but the fields are blank. Like it sees the
records, but its not getting put into the partial. 2) After I get the
addresses displayed, how would I go about saving the contact and all of
the addresses in a single post-back?

I’ve been googling for days, and it seems this should be a simple thing
that has been encountered before.

Thanks in advance for your help!

Josh Huckabee wrote:

Additionally, in my contacts_controller.rb ‘edit’ method, I have the
following to include the address information

def edit
@contact = Contact.find(params[:id], :include => :addresses)
end

Anyone trying to accomplish this should check out the Sub-List form
plugin (link above). Solves my issue and works great!

In case someone else stumbles along this post, I have found a plugin and
a generator that might fit my needs. Since RubyForge is down, I haven’t
been able to download and install. I will update with what I find.

Sub-List Form Plugin:
http://wiki.rubyonrails.com/rails/pages/Sub-List+Form+Plugin

Ajax Scaffold Generator:
http://www.ajaxscaffold.com/

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs