Re: can this be done without using find_by_sql

Phlip
Sat, 14 Feb 2009 11:53:05 -0000

Frederick Cheung wrote:

>> Repair has_many :notes
>>
>> SELECT * FROM repairs
>> where exists
>> (select * from notes where repairs.id=notes.repair_id
>>           and  and notes.flagged)

I forgot my basic SQL! I think that''s just

  SELECT * FROM repairs r, notes n
   WHERE r.id = n.repair_id
     AND n.flagged = 1

right?

   Repair.all( :include => :notes,
            :conditions =>{ ''notes.flagged'' => true } )

"Find all repairs with any flagged notes". And I thought AR would
handle
distinct-ing that.

So how to do a sub-select if you indeed need one?

But my other answer lets you trivially walk back from the notes to the repairs:

   r.notes.find_by_flagged(true).map(&:repair)

Warning: A map{} that rips another model like that can grow inefficient!

--
   Phlip