Reputation: 661
On my dashboard I'm trying to render a partial as a table (index)
My partial: _transaction.html.erb That partial is actually an index, based on transactions index. It should return all transactions in a table. My partial contains:
<% @transactions.each do |transaction| %>
<tr>
<td><%= transaction.transaction_type %></td>
<td><%= transaction.date %></td>
</tr>
<% end %>
The error I receive:
"You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.each"
Upvotes: 1
Views: 1214
Reputation: 4799
That would seem to indicate that your TransactionsController#index
action is not returning anything for @transactions. The most obvious cause is that whatever logic you are using to find records is broken, returning 0 results, or not setting @transactions correctly.
In views like that, you want to do an error check for the situation where you have no results (or an error of some sort).
Your index.html view:
<% if !@transactions || @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 %>
Your _transaction.html.erb partial:
<tr>
<td><%= transaction.transaction_type %></td>
<td><%= transaction.date %></td>
</tr>
That will get your view working again. The next step is to figure out why your controller action is not returning results. Start by opening a rails console and trying to retrieve records:
>> Transaction.all
If that returns any results, then you have data. If not, create a record either via a web interface you've developed or via the rails console:
>> 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
Once you have a record, test your view again. If it still fails, you probably have an error in your controller logic. As to what that error could be, you'll need to post it for us to help you with that. :)
Upvotes: 2