从单个表单创建多个关联记录

Creating multiple associated records from a single form

我有一个创建列表的表单 - 但我希望它创建一些关联记录。我的模型结构如下:

当我提交此表单时,我想一次性创建一个列表、一张卡片和一家公司。验证也应该是 运行.

现在我明白了,如果我想在我的列表表单中包含一个 Card 字段,我将使用类似的东西:

@card = @listing.cards.build
[...]
fields_for(@listing, @card) do |c|

但是如果我想在表单中包含公司字段,我该怎么办?我检查了,但是 @card.company 是零。

你应该使用 fields_for 表单助手 http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for

或者使用像这样的宝石 https://github.com/ryanb/nested_form

简答:

构建 card 不会自动创建关联的 company

长答案

恕我直言,最合理的方法是从 company 开始并围绕它创建关联 ,如果您想创建 listing,甚至

这样看:

  • listingcompany 可以独立存在
  • card 假设存在 company
  • a listing 和 a card 通过联接关联 table

因此:如果你想创建一个 listing 有一个关联的 card,你还需要一个 company 属于 card。因此,我们会将公司放在层次结构的顶部并执行如下操作:

class CompanyController < ApplicationController
  ...
  def new
    @company = Company.new
    @card = @company.cards.build
    @listing = @card.listings.build
  end
  ...
end

分别在嵌套表单中,company 位于顶部,card 位于其后,listing 位于最后:

= form_for @company do |company_f|
  - # company stuff
  = company_f.fields_for @card do |card_f|
    - # card stuff
    = card_f.fields_for @listing do |listing_f|
      - # listing stuff