Rails 如何将现有产品作为嵌套属性添加到发票中?

How to add existing product into invoices as nested attributes in Rails?

我已经在 Rails 中阅读了有关嵌套属性的内容,到目前为止,我发现 gems cocoon 满足我对嵌套属性的分发形式的需求,并且可以完成目前的所有实现。但我想尝试通过使用 Cocoon 搜索产品数据,将现有数据产品作为嵌套属性添加到发票表格中。我应该怎么做才能在 Rails?

中完成这些表单交互

像这张图我猜的例子: image

更新

Invoice.rb

class Invoice < ApplicationRecord
  has_many :products, inverse_of: :invoice
  accepts_nested_attributes_for :ticket_details, reject_if: :all_blank, allow_destroy: true
end

Product.rb

class Product < ApplicationRecord
  belongs_to :category
  belongs_to :tax
  belongs_to :invoice
end

要使用 nested attributes,您需要对模型、视图和控制器进行更改:

型号: 您的型号需要指定 accepts_nested_attributes_for(在您的情况下,请将产品更改为 ticket_details)

class Invoice < ApplicationRecord
  has_many :products, inverse_of: :invoice
  accepts_nested_attributes_for :products, reject_if: :all_blank, allow_destroy: true
end

查看: 使用 fields_for 生成您的 products_attributes 参数

<%= form_for @invoice do |form| %>

  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name, id: :user_name %>
  </div>

  <%= form.fields_for :products, @invoice.products do |product| %>
    <%= product.text_field :name %>
  <% end %>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

控制器:允许参数products_attributes

def invoice_params
  params.require(:invoice).permit(:name, products_attributes: [:name, :id])
end