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

243 views Asked by At

I have 3 models, first product model, invoice and invoice_detail.

Invoice(Parent) and invoice detail(Child) are nested resource.

Am adding products from invoice detail model, that's working fine, the problem is when am trying to display in a table the name of the product that was added, am getting the follow error:

Thanks in advance!!

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
1

There are 1 answers

1
Andy On BEST ANSWER

In your view,

<%= invoice_detail.product_id.name %>

should be

<%= invoice_detail.product.name %>