Reference Through records in a has many through join

I have 2 tables (toms and dicks) joined with has_many through a third
table (harries).

@tom = Tom.find(1)

How do you reference all the related records in harries. If I do:

@tom.dicks[1].harries

I get records for all records in tom, not just for @tom i.e. with an
id of 1.

Many thanks,

Mike

Thanks very much for the thorough response. It surprises me that
having declared:

@tom= Tom.find(1)

there is not a more direct route to accessing related harries.

Heh ho,

more thanks,

Mike

Having declared @tom= Tom.find(1), you can access @tom.harries which
is an array of Harry object where tom_id = 1.
I though you want to access directly to the related dicks of @tom.

Sorry for misundertanding

Mathieu BODIN

It depends on what you configured as relations between those objects :
I guess you might have something like that :
class Tom < …(whatever ActiveRecord)
:has_many :harries
:has_many :dicks, :througt => :harries
end

class Dick< …(whatever ActiveRecord)
:has_many :harries
:has_many :toms, :througt => :harries
end

class Harry < …(whatever ActiveRecord)
:belongs_to :tom
:belongs_to :dick
end

(I’m not really sure of the correctness of what is written but it’s
not the point)

Let’s assume that migrations are ok
So what’s up @tom, let’s say @tom is defined as you proposed
@tom= Tom.find(1)

now you can access the dicks of @tom (haha!!) like this
@tom.dicks

so if you want a specified one, you can do something like that

@tom.dicks[42] # it will return the 42 Dick instance of the Array
represented in @tom.dicks

As this one is an Dick instance, you still have access to his harries,
like this
@tom.dicks[42].harries

And if you want a specific Harry instance, you may try something like
the following
Harry.find(:first, :conditions => [ "tom_id = ? AND dick_id = ? ", 1,
@tom.dicks[42].id])

Hope it helps

Mathieu BODIN