简体   繁体   中英

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.

在 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM