【问题标题】:How to add existing product into invoices as nested attributes in Rails?如何将现有产品作为 Rails 中的嵌套属性添加到发票中?
【发布时间】:2019-06-20 18:05:38
【问题描述】:

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

就像这张图片我猜的例子: image

更新

发票.rb

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

产品.rb

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

【问题讨论】:

  • 你应该提供一些你的代码,例如:你的模型
  • 嗨,我已经更新了我的代码模型

标签: javascript ruby-on-rails ruby postgresql nested-attributes


【解决方案1】:

要使用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

【讨论】:

  • 是的,我错误地声明了模型。在其他情况下,如果我们要从发票表单上的现有产品中进行选择,而不仅仅是在发票中添加新产品,如何实现?
  • form.fields_for :products, @invoice.products 将为您提供与发票相关的所有现有产品
  • 我已经声明了#products_field = f.simple_fields_for :products, @invoice.products do |product| .nested_fields = product.text_field :代码。但是为什么似乎没有显示表单 fields_for products?
猜你喜欢
  • 2012-05-21
  • 2018-05-04
  • 1970-01-01
  • 2019-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多