如何使用嵌套资源显示来自另一个模型的模型字段 rails 5

How to display model fields from another model using nested resource rails 5

我有 3 个模型,第一个产品模型,发票和 invoice_detail。

发票(父)和发票明细(子)是嵌套资源。

我正在从发票明细模型添加产品,工作正常,问题是当我尝试在 table 中显示已添加产品的名称时,出现以下错误:

提前致谢!!

invoices/show.html.erb

undefined method `name' for 2:Integer

invoices/show.html.erb

<% @invoice.invoice_details.each do |invoice_detail| %>
        <tr>
          <td><%= invoice_detail.product_id.name %></td>
          <td><%= number_to_currency invoice_detail.product_id.price %></td>
          <td><%= invoice_detail.product_id.quantity %></td>
          <td><%= number_to_currency invoice_detail.total_amt %></td>

          <td>


              <%= link_to "Destroy", 
                                    [@invoice, invoice_detail],
                                    method: :delete,
                                    remote: true,
                                    data: { confirm: "Are you sure?" },
                                    class: "btn btn-default"%> 
          </td>
         </tr>
        <% end %>

models/product.erb

class Product < ApplicationRecord
  belongs_to :category
  belongs_to :brand
  belongs_to :unit
  belongs_to :warehouse
  belongs_to :user
  has_many :invoice_details
end

models/invoice.erb

class Invoice < ApplicationRecord
  belongs_to :warehouse
  belongs_to :invoice_type
  belongs_to :user
  belongs_to :customer
  belongs_to :provider
  has_many :invoice_details, :dependent => :destroy
end

models/invoice_detail.erb

class InvoiceDetail < ApplicationRecord
  belongs_to :invoice
  belongs_to :product
  belongs_to :tax
end

在您看来,

<%= invoice_detail.product_id.name %>

应该是

<%= invoice_detail.product.name %>