each_with_index正在输出数组

时间:2011-08-22 22:15:23

标签: ruby-on-rails ruby-on-rails-3

我有一个rails应用程序,它通过以下方式调用视图中的辅助方法:

 <%= link_to_receipts @purchase_request %>

在我的帮手中:

link_to_receipts purchaserequest
   purchaserequest.receipts.each_with_index do |receipt,i|
     #some code here commented out...
   end
end

但它在视图上输出数组:

  
    

[#&gt; tagged_by:“joe somebody”,purchase_request_id:39,created_at:“2011-08-22 20:39:18”,updated_at:“2011-08-22 20:39:18”&gt;]

  

如果我注释掉each_with_index,它将不会显示数组,但如果存在则会显示数组。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我发现了问题。在帮助器方法中,我首先在块中初始化变量html,如下所示:

link_to_receipts purchaserequest
    purchaserequest.receipts.each_with_index do |receipt,i|
     html = ""
     #more code here
    end
 end

当它应该在块之外声明时:

link_to_receipts purchaserequest
html = ""
    purchaserequest.receipts.each_with_index do |receipt,i|
     #code here
    end
 end