Home > other >  Ruby on Rails // Getting a Strange Return on .each loop
Ruby on Rails // Getting a Strange Return on .each loop

Time:04-01

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.

CodePudding user response:

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 it is doing, and you're outputting it with <%=.

  • Related