views:

225

answers:

3

I am developing a webapp (well trying to) in Ruby on Rails.

I have a partial render in my index.html.erb

<%= render :partial => "houses/index", :locals => @houses %>

index.html.erb is loaded when the user hits the root of my domain. This partial cause this error:

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

Extracted Source around line 8

5:     <th>Washrooms</th>
6:   </tr>
7: 
8: <% @houses.each do |house| %>
9:   <tr>
10:     <td><%=h house.short_desc %></td>
11:     <td><%=h house.bedrooms %></td>

Trace of template inclusion: app/views/home/index.html.erb

All I would like to is display 5 houses on my Homepage (index.html.erb)

What am I missing to get this to work?

Many thanks

EDIT:

Houses_controller

NoMethodError in Home#index

Showing app/views/houses/_index.html.erb where line #10 raised:

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

Extracted source (around line #10):

7: Washrooms 8: 9: 10: <% @houses.each do |house| %> 11: 12: <%=h house.short_desc %> 13: <%=h house.bedrooms %>

Trace of template inclusion: app/views/home/index.html.erb

+5  A: 

The value of :locals is supposed to be a Hash that defines local variables. So

<%= render :partial => "houses/index", :locals => {:houses => @houses} %>

and then

<% houses.each do |house| %>

To reiterate, since the new error you posted shows that you are still not doing it correctly:

If you're passing it through :locals, you want houses.each, not @houses.each. No snail. Local variables don't have a @ prefix; instance variables do.

Chuck
+2  A: 

Locals takes a hash of local variables, like so:

<%= render :partial => "houses/index", :locals => { :houses => @houses } %>

Also, when you pass in a local variable to a partial, you should use it as a local variable rather than an instance variable within the partial, as so:

<% houses.each do |house| %>
# do stuff with each house
<% end %>
Phil
This is returning the same error? Do I want to place the above code in my app/views/home/index.html.erb? Thanks again
Crankyadmin
@Crankyadmin: It's a replacement for the code you posted above. **Is** `@houses` set to anything meaningful in your controller?
Chuck
I have added more information. _index.html.erb exists. I have linked to my houses controller. Thanks again!
Crankyadmin
A: 

You don't need to pass it in :locals if it's an instance variable. Instance variables are available in all partials.

In your view:

<% @houses.each do |house| %>
  # do stuff with each house
<% end %>
Ryan Bigg