Basic question about belongs_to

Hello,

I’ve got three tables:

site {
id
name,
customer_id
}

building {
id,
site_id,
name
}

equipment {
id,
building_id,
name
}

In my building model I have “belongs_to :site” and in my equipment
model I have “belongs_to :building”.

How do I find all pieces of equipment that belong to a particular
customer?

I tried something like Equipment.find(:all, :include =>
[ :building, :site ], :conditions => ‘customer_id = 1’), but of course
that doesn’t work because there’s nothing about :site in the equipment
model. I also tried to put “:include => :site” in the “belongs_to” in
the building model, but I got an error saying that the association
named “:site” wasn’t found.

Any ideas?

Thanks!

Where’s Customer?
I tried to shorten my question, that’s why I didn’t show all the
relevant relationships. I do have the customer model.

Your table names should be plural (e.g., ‘sites’ and ‘buildings’)
They are. They aren’t in the example though. Good catch :slight_smile:

Equipment.find(:all, :include => { :building => :site }
This worked like a charm. I need to read about that variation
of :include. Cool!

(adding “has_many” associations to mirror your “belongs_to”; having a
Well, so far I haven’t needed to reverse. Is that a no-no not to
mirror it?

Thanks Rob. You saved me a lot of searching. Much appreciate.

On Jul 4, 2007, at 1:08 PM, surge wrote:

building {

Where’s Customer?

In my building model I have “belongs_to :site” and in my equipment
model I have “belongs_to :building”.

How do I find all pieces of equipment that belong to a particular
customer?
Do you also have:
class Site
has_many :buildings
end
and so on?
Thanks!
Your table names should be plural (e.g., ‘sites’ and ‘buildings’)
unless you have overridden this with set_table_name in your model.

You can also try:

Equipment.find(:all, :include => { :building => :site },
:conditions => [ ‘site.customer_id = ?’,
some_customer ])

but even if that works as-is, you should consider the other parts
(adding “has_many” associations to mirror your “belongs_to”; having a
customer model and table; pluralizing your tables) as means to avoid
future aggravation.

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

Well, so far I haven’t needed to reverse. Is that a no-no not to
I meant to say “I haven’t needed the reverse relationship”