Rails updating several models in one form

I am writing a form that uses formtastic to manage a BusinessUnit model, however, when creating a new BusinessUnit, you also need to create a number of other record types. The relationships between the models are shown below:

class BusinessUnit < ActiveRecord::Base
  has_many :business_unit_sites
  has_many :locations

class BusinessUnitSite < ActiveRecord::Base
  belongs_to :site
  belongs_to :business_unit

class Site < ActiveRecord::Base
  has_many :locations
  has_many :business_unit_sites

class Location < ActiveRecord::Base
  belongs_to :business_unit
  belongs_to :site 

When BusinessUnit is created, the site must also be created using BusinessUnitSite as the connection table. In addition, a location record must be created that must contain the foreign key for the new site record, and here I am having problems.

I can create a new location using the attached form (below), but the site must be created manually.

<%= semantic_form_for @business_unit do |f| %>
  <%= f.inputs do %>
    <%= f.input :name %>
    <%= f.input :business_unit_id %>
    <%= f.input :business_unit_group, :include_blank => false %>
    <%= f.input :business_unit_type %>
    <%= f.input :tax_region, :include_blank => false %>
    <%= f.semantic_fields_for :locations do |l| %>
      <%= l.input :name, :label => "Location Name" %>
    <% end %>
  <% end %>
  <%= f.buttons %>
<% end %>

What is the best way to create Location, Site records and ensure that Location contains the foreign key of the site you just created?

+3

All Articles