Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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 :

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 <%=.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading