luissimo luissimo - 1 month ago 11x
Ruby Question

undefined method for ActiveRecord_Associations_CollectionProxy [rails]

i'm building an invoice application and in the

partial i made the invoice where users can add products including quantity, description and unitprice. And users can add extra rows to add more items(products).

Now when i try to display that information in the show view like this:

<tr class="products_tr">
<td> <%= @invoice.products.quantity %> </td>
<td> <%= @invoice.products.description %> </td>
<td> <%= @invoice.products.unitprice %> </td>
<td class="row_total"><%= @invoice.products.quantity * @invoice.products.unitprice %></td>
<td> <%= @invoice.products.btw %> </td>

it gives out the next error:

undefined method `quantity' for #<Product::ActiveRecord_Associations_CollectionProxy:0x007fbe92831500>

This is the code in the controller;

def show

Any idea on how to fix this? help would be much appreciated. And plus points for an explanation on what it is exactly that i'm doing wrong.


If i loop through the @invoice.products like Michał Młoźniak said it works but it also shows an extra row that contains nil, like this:
enter image description here


You said yourself that invoice can have many products so you need a loop to iterate over this list of products.

  <% @invoice.products.each do |product| %>
    <% if product.persisted? %>
      <tr class="products_tr">
        <td> <%= product.quantity %> </td>
        <td> <%= product.description %> </td>
        <td> <%= product.unitprice %> </td>
        <td class="row_total"><%= product.quantity * product.unitprice %></td>
        <td> <%= product.btw %> </td>
    <% end %>
  <% end %>