I have 2 tables (toms and dicks) joined with has_many through a third
@tom = Tom.find(1)
How do you reference all the related records in harries. If I do:
I get records for all records in tom, not just for @tom i.e. with an
id of 1.
Thanks very much for the thorough response. It surprises me that
there is not a more direct route to accessing related harries.
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
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 :dicks, :througt => :harries
class Dick< …(whatever ActiveRecord)
:has_many :toms, :througt => :harries
class Harry < …(whatever ActiveRecord)
(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
now you can access the dicks of @tom (haha!!) like this
so if you want a specified one, you can do something like that
@tom.dicks # 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,
And if you want a specific Harry instance, you may try something like
Harry.find(:first, :conditions => [ "tom_id = ? AND dick_id = ? ", 1,
Hope it helps