Iterating over Instance variable printing unwanted things [duplicate]

僤鯓⒐⒋嵵緔 提交于 2020-01-15 09:45:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!