Reputation: 6412
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
Upvotes: 0
Views: 74
Reputation: 2606
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.
Upvotes: 2
Reputation: 11811
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
Upvotes: 2