Rails的一个表单上更新多个模型 [英] Rails updating multiple models on a single form

查看:149
本文介绍了Rails的一个表单上更新多个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写它使用formtastic管理BusinessUnit模型的形式,创建一个新的BusinessUnit它也有创造了许多其他记录类型然而,当。该模型之间的关联是如下:

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 

在创建BusinessUnit,一个站点还必须使用BusinessUnitSite作为连接表中创建。另外一个位置记录应创建其必须持有的外键到新的站点记录,这就是有问题即时通讯。

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?

推荐答案

您可能需要做一些像用在子对象的 fields_for 的方法你形式。

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

请参阅此相关的答案: 在Rails形式多个对象

See this related answer: Multiple objects in a Rails form

关于fields_for更多信息:

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

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

这篇关于Rails的一个表单上更新多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆