'Ruby on Rails // Getting a Strange Return on .each loop

I am making a shopping cart for a web app. So far it has 3 components: 'products', 'line_items' and 'carts'. The flow seems to be okay. I am getting all the returns I want. But, after the .each loop, I am getting a return of the entire product model.

What is showing when rendered in Chrome

The code being rendered:

<hr>
<%= @cart.line_items.each do |line_item| %>
   <%# binding.pry %>
   Item: <%= line_item.product.name %><br>
   Price: <%= line_item.product.price %><br>
   Quantity: <%# line_item.quantity %><br>
   <hr>
<% end %>
<hr>

What I can't figure out is why this bit at the end is rendered. When I run a binding.pry to inspect the '@cart' I can't find this final return. It looks like it is returning the product models as an array.

I am not sure what other parts of the code that would be helpful. It is currently up to date on GitHub if you want to have a look. Thank you in advance.



Solution 1:[1]

Use <% foo.each in your views, not <%= foo.each.

The later executes the loop, and then outputs the return value of foo.each, which is foo (the collection itself).

It looks like it is returning the product models as an array.

That is exactly what for.each does. Using <% will cause the return value to be silently discarded, while <%= outputs it to the browser.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1