Crankyadmin
Crankyadmin

Reputation: 155

Ruby and Nil Object

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

Upvotes: 0

Views: 3582

Answers (3)

Chuck
Chuck

Reputation: 237010

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.

Upvotes: 4

Ryan Bigg
Ryan Bigg

Reputation: 107708

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 %>

Upvotes: 0

philnash
philnash

Reputation: 73029

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 %>

Upvotes: 2

Related Questions