Rails updating multiple models on a single form

2019-05-15 06:23发布

问题:

Im writing a form which uses formtastic to manage the BusinessUnit model, however when creating a new BusinessUnit it also has to create a number of other record types. The associations between the models are as 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 a BusinessUnit is created, a Site must also be created using BusinessUnitSite as a join table. In addition a Location record should be created which must hold a foreign key to the new Site record and this is where Im having problems.

I can create a new Location using a nested form (below) but the Site will have to 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 the Location, Site records and ensure that Location holds the foreign key of the newly created Site?

回答1:

You probably want to do something like using the "fields_for" approach for the sub-objects in your form.

See this related answer: Multiple objects in a Rails form

More info about fields_for:

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html

http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for