问题
My questions details are here
undefined method `items' for nil:NilClass in @cart.items.each
The extra things I added were a cart method in application controller and also made it helper_method to make it available in all views across the application
helper_method :cart
def cart
@cart = Cart.find(session[:cart_id])
end
When in my view I iterate over the @cart variable like this
<%= cart.items.each do |item| %>
<tr>
<td><%= item.product.title%></td>
<td><%= item.product.price%></td>
</tr>
<% end %>
It shows this
Why is printing that upper thing? I know that is the output of item.product.title and all such variables. How to remove that?
回答1:
Why is printing that upper thing?
Because you are telling it to. When you surround ruby code with <%= %>
you are telling it to render the result of the enclosed code. Since you are putting it around the each
block it is displaying the result of each
, which is the collection it was called on.
To remove it, just use <% %>
instead.
来源:https://stackoverflow.com/questions/17955135/iterating-over-instance-variable-printing-unwanted-things