Why won't this array populate?

Taylor Strait wrote:

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:

<h1>Room Info</h1> <% unless @room.nil? %>   <ul>     <% for room in @rooms %>        <li><%= @room.name %>     <% end %>   </ul> <% 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?

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:

<ul>   <% for room in @rooms %>     <li><%=h room.name %></li>   <% end %> </ul>

I hope that helps man!

Cheery-o Gustav Paul gustav@rails.co.za

Gustav Paul <gustav@...> writes:

def show    <at> unit = Unit.find(params[:id])   session[:unit_id] = <at> unit.id    <at> rooms = <at> unit.rooms #assuming as you say unit "has_many :rooms" end

And in the view do the following:

<ul>   <% for room in <at> rooms %>     <li><%=h room.name %></li>   <% end %> </ul>

No need to even set an instance variable

<ul>    <% for room in @unit.rooms %>      <li><%=h room.name %></li>    <% end %> </ul>

Gareth