Topic: Problem with a list

Ok, here's what I'm trying to do. I've got an application that will display a list of apartments. The database is broken down like this:

Area (id, name) has_many :buildings
Building (id, address, area_id) belongs_to :area, has_many :apartments
Apartment (apt_number, building_id) belongs_to :building

I've got a controller called Listing that works with the Apartment model. The Listing index.rhtml file basically just shows a list of the areas by name (ie: North, South, East, West). What I would like is to be able to click on one of the areas and have it display a simple table of just the apartments in that particular area.

What I think I should be able to do is have the link call the list method, which would then sort the data by the area id (apartment.building.area_id). But when I tried using :conditions => "building.area_id = '3', it locked up. Also, I'm not entirely sure how to pass an argument to the list method from the list of areas, or if that is even possible.

Any suggestions on how I can make this work?

Re: Problem with a list

Hmm, I think there is something even easier, but this should work

@apartment_list = (Apartment.find :all).find_all { |a| a.building.area_id = 3}

The reason why your :conditions base approach failed is that the database can't reach through the model objects (ie building.area_id doesn't make sense to the DB).

My RoR journey  -- thoughts on learning RoR and lessons learned in applying TDD and agile practices.

Re: Problem with a list

You can pass the area's id along with the link like this (you may need to adjust it to fit your circumstances).

<%= link_to area.name, :action => 'area', :id => area %>

Then in your controller for the "area" action (or whichever you call it):

def area
  @area = Area.find(params[:id])
end

Then in your area.rhtml view:

<h1>Apartments in <%=h @area.name %></h1>
<ul>
<% for apartment in @area.apartments %>
  <li><%=h apartment.name %></li>
<% end %>
</ul>

There's one more change you need to make because @area doesn't have "apartments", it has buildings. You need to define a :through relationship in Area to give it many apartments through buildings. Like this:

class Area < ActiveRecord::Base
  has_many :buildings
  has_many :apartments, :through => :buildings
end

Hope that works for you.

Last edited by ryanb (2006-08-11 17:14:09)

Railscasts - Free Ruby on Rails Screencasts

Re: Problem with a list

I added the line "has_many :apartments, :through => :buildings" to my Area.rb file, but now when I try to run the application, I get an error that says "Unknown key(s): through". I checked the Ruby on Rails wiki for ThroughAssociation and it looks like I did it correctly. Any ideas what went wrong?

Re: Problem with a list

What version of rails to do you have?

My RoR journey  -- thoughts on learning RoR and lessons learned in applying TDD and agile practices.