luissimo
luissimo

Reputation: 978

undefined method for ActiveRecord_Associations_CollectionProxy [rails]

i'm building an invoice application and in the _form 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:

    <tbody>
     <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>
     </tr>
    </tbody>

it gives out the next error:

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

This is the code in the controller;

  def show
    @invoice.products.build
    @invoice.build_customer
  end

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.

EDIT

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

Upvotes: 0

Views: 1093

Answers (2)

Michał Młoźniak
Michał Młoźniak

Reputation: 5556

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

<tbody>
  <% @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>
      </tr>
    <% end %>
  <% end %>
</tbody>

Upvotes: 1

pk-n
pk-n

Reputation: 576

your @invoice.products is a collection where as you should calling quantity on each object in that collection.

Upvotes: 0

Related Questions