views:

32

answers:

2

Hi

I've got an organisation database table which holds the following fields:

organisationid, organisationname, organisationaddressid, mainadminname, mainadminaddressid.

The two address ids are pointers to two records within the address database table. The address database table conatins the following fields:

addressid, addressline1, addressline2, addresstowncity, addresspostcode.

So when I create new organisation I want to capture the following information:

organisationname
organisationaddressline1
organisationaddressline2
organisationaddresstowncity
organisationaddresspostcode
mainadminname
mainadminaddressline1
mainadminaddressline2
mainadminaddresstowncity
mainadminaddresspostcode

And when I save this information I want to create 1 organisation record and two address records.

I'm at a loss on how to do this in ROR!

Any suggestions gratefully recieved.

Thanks for your time

Sniffer

+2  A: 

I think that helps you:

http://railscasts.com/episodes/196-nested-model-form-part-1

http://railscasts.com/episodes/197-nested-model-form-part-2

Lichtamberg
Didn't have time to watch these, but Railscasts looks a great resource. Thanks for sharing!
Sniffer
+2  A: 

Not quite standard looking rails column names, so I'm guessing you may be working with a legacy DB, at any rate:

Assuming that your Organization model was something like this:

belongs_to :organization_address, :class_name => 'Address', :foreign_key => 'organisationaddressid'
belongs_to :main_admin_address, :class_name => 'Address', :foreign_key => 'mainadminaddressid'

# See http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
# Make the organization accept nested attributes for the addresses
accepts_nested_attributes_for :organization_address, :main_admin_address

Your form would probably look something like this with fields_for the different addresses:

<% form_for Organization.new do |f| %>
  <%= f.text_field :name %><br />
  <% fields_for :organization_address do |oaf| %>
    <%= oaf.text_field :addressline1 %><br />
    <%= oaf.text_field :addressline2 %><br />
    ...
  <% end %>
  <%= f.text_field :name %><br />
  <% fields_for :main_admin_address do |maaf| %>
    <%= maaf.text_field :addressline1 %><br />
    <%= maaf.text_field :addressline2 %><br />
    ...
  <% end %>
<% end %>

After that, in your controller

@organization = Organization.new(params[:organization])
@organization.save

Should save the organization model as well as the two address models.

njorden
Got there eventually - this answer got me on the correct path, alomg with this article - http://www.pixellatedvisions.com/2009/03/18/rails-2-3-nested-model-forms-and-nil-new-record - especially the bit regrading to the solution to a similar problem I faced. Thanks for pointing me in the correct direction njorden.
Sniffer