Find all object through another object - how?

I’m trying to find all “apples” that belong to user_id 2.

But the “apples” table doesn’t have a “user_id” column; it has a
“fruit_id” column, that points to a “fruit” object.

The “fruit” table has a “user_id” column.

So how would I set something up like this to find all the “apples” that
belong to user_id 2?

@apples = Apple.find(:all, :conditions => [“fruit.user_id = 2”])

Joe P. wrote:

I’m trying to find all “apples” that belong to user_id 2.

But the “apples” table doesn’t have a “user_id” column; it has a
“fruit_id” column, that points to a “fruit” object.

The “fruit” table has a “user_id” column.

So how would I set something up like this to find all the “apples” that
belong to user_id 2?

@apples = Apple.find(:all, :conditions => [“fruit.user_id = 2”])

Just in case someone’s wondering, I already have the right connections
in the models (like :belongs_to, :has_many). So that’s not the problem.

On 1 Nov 2007, at 19:09, Joe P. wrote:

that
belong to user_id 2?

@apples = Apple.find(:all, :conditions => [“fruit.user_id = 2”])

Just in case someone’s wondering, I already have the right connections
in the models (like :belongs_to, :has_many). So that’s not the
problem.
Well with a has_many :through you could just do User.find(2).apples
If you don’t want to do that then you’ll have to write down the
appropriate join.

Fred

On 11/1/07, Joe P. [email protected] wrote:

@apples = Apple.find(:all, :conditions => [“fruit.user_id = 2”])

You need to join the fruits table to the query. One way to do this is

@apples = Apple.find(:all, :include => :fruits, ::conditions =>
[“fruit.user_id = 2”])

You could also use a :joins string to manual add the sql join clause,
but this has the side effect of making the resultant Apple read only
since it will contain bogus fields from the fruit table.


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/