如何使用嵌套表单和 has_many :through 添加和编辑多个模型

How to add and edit multiple models with nested forms and has_many :through

我相信我已经阅读了有关 SO 的所有相关答案,但仍未找到解决方案,所以这是我的问题。我有 'inherited' 一个用于处理产品、批次和数量的应用程序。一个批次将有许多产品,产品可以出现在许多批次和许多数量中。所以 has_many :through 关系是隐含的,因为联接 table 将有一个额外的产品数量列;

class Batch < ActiveRecord::Base
  has_many :quantities
  has_many :products, :through => :quantities
  accepts_nested_attributes_for :products
end

class Product < ActiveRecord::Base
  has_many :quantities
  has_many :batches, :through => :quantities
  accepts_nested_attributes_for :quantities
end

class Quantity < ActiveRecord::Base
  belongs_to :product
  belongs_to :batch
end

现在,假设我需要创建一个新批次。我希望用户能够指定要出现在批次中的产品,以及每个产品的数量。

如何设置我的表格以便同时指定产品和数量?我可能还需要控制器和表单的一些细节。在 'new' 操作中,我可以构建所需的模型;

@batch = Batch.new
@qty = @batch.quantities.build.build_product

但随后我对表格感到困惑 - 应如何指定字段?

<%= form_for(@batch) do |f| %>
    <% f.fields_for :products do |prod_form| %>
        <% prod_form.fields_for :quantity do |qty_form| %>
        <% end %>     
    <% end %> 
<% end %> 

答案与找到的相同here

has_one 和 has_many 关联的构建方法签名不同。

class User < ActiveRecord::Base
  has_one :profile
  has_many :messages
end

has_many 关联的构建语法:

user.messages.build

has_one 关联的构建语法:

user.build_profile  # this will work

user.profile.build  # this will throw error

阅读 has_one 协会文档了解更多详情。