2011-01-22 65 views
1

在我的仪表盘我试图渲染部分作为表(指数)如何使部分指数在Rails3中

我的部分:_transaction.html.erb 这部分实际上是一个指数,根据交易指数。它应该返回表中的所有事务。我的部分包括:

<% @transactions.each do |transaction| %> 
    <tr> 
    <td><%= transaction.transaction_type %></td> 
    <td><%= transaction.date %></td> 
    </tr> 
    <% end %> 

我收到的错误:!

“你有一个零对象时,你没想到吧 你可能期望阵列的一个实例,在评估时发生 错误nil.each“

+0

看来你没有设置@transactions变量。你确定你把它放在控制器上吗?也许在名字之前忘了@ – tomeduarte 2011-01-22 17:34:45

回答

2

这似乎表明您的TransactionsController#index操作没有为@transactions返回任何内容。 最明显的原因是,无论您用于查找记录的逻辑是否被破坏,返回的结果为0,或者没有正确设置@transactions。

在这样的视图中,您希望对没有结果(或某种错误)的情况进行错误检查。

您的index.html观点:

<% if [email protected] || @transactions.length == 0 %> 
    <p>'No transactions found.'</p> 
<% else %> 
    <table> 
     <!-- put your column headers here --> 
     <!-- the next line iterates through each transaction and calls a "_transaction" partial to render the content --> 
     <%= render @transactions %> 
    </table> 
<% end %> 

你_transaction.html.erb部分:

<tr> 
    <td><%= transaction.transaction_type %></td> 
    <td><%= transaction.date %></td> 
</tr> 

这将让你的看法再次合作。下一步是弄清楚为什么你的控制器操作没有返回结果。首先打开轨道控制台并尝试检索记录:

>> Transaction.all 

如果返回任何结果,则表示有数据。如果没有,或者通过你开发一个Web界面或通过铁轨控制台创建一个记录:

>> t = Transaction.new() 
>> t.transaction_type = 1 #or whatever is appropriate for your application 
>> t.date = Date.today 
>> t.valid? #if true, your record will save. If not, you need to fix the fields so they validate 
>> t.save 

一旦你有一个记录,再次测试你的看法。如果仍然失败,那么您的控制器逻辑中可能有错误。至于那个错误可能是什么,你需要将它发布给我们来帮助你。 :)

+0

谢谢Shaun。奇迹般有效。如何更新我的视图以通过范围显示事务? – Olivier 2011-01-22 18:42:10