Why won't this array populate?

Units have many rooms. Rooms belong to units. When I show the detail
of a unit, I want to show a list of rooms belonging to the unit as well.
In the UnitController:

def show
@unit = Unit.find(params[:id])
session[:unit_id] = @unit.id
@room = Room.find(:all,
:conditions => [ “unit_id = ?”, @unit[:id] ])
end

In /units/show.rhtml:

Room Info

<% unless @room.nil? %>
    <% for room in @rooms %>
  • <%= @room.name %> <% end %>
<% end %>

Yet I still get this exception:

NoMethodError in Units#show

You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.each

Questions:

  1. Why do I have a nil array?
  2. Even if I have a nil array, why doesn’t <% unless @room.nil? %> stop
    it?

Because in show you are using @rooms which you haven’t set anywhere

Fred

Taylor S. wrote:

<% end %>

Questions:

  1. Why do I have a nil array?
  2. Even if I have a nil array, why doesn’t <% unless @room.nil? %> stop
    it?

Hey

Nowhere in your action is @rooms defined…

I think it should look as follows:

def show
@unit = Unit.find(params[:id])
session[:unit_id] = @unit.id
@rooms = @unit.rooms #assuming as you say unit “has_many :rooms”
end

And in the view do the following:

    <% for room in @rooms %>
  • <%=h room.name %>
  • <% end %>

I hope that helps man!

Cheery-o
Gustav P.
[email protected]

Gustav P. <gustav@…> writes:

<li><%=h room.name %></li>

<% end %>

No need to even set an instance variable

    <% for room in @unit.rooms %>
  • <%=h room.name %>
  • <% end %>

Gareth

Fred:
You are right. A simple typo caused most of it.

Gustav:
Your way is much neater! Why bust my fingers when ActiveRecord can do
it for me? Thanks!