Re: can this be done without using find_by_sql

Frederick Cheung
Sat, 14 Feb 2009 11:44:47 -0000

On 14 Feb 2009, at 11:33, tonypm wrote:

>
> Hi,
>
> I am increasingly needing to do some more complex finds involving
> several table associations.  I can usually find an SQL solution, but
> find it hard to think these out using ActiveRecord find techniques.  I
> guess I am thinking in SQL terms, when perhaps there is a way of
> thinking in ActiveRecord terms.  Here is an example, I am guessing
> this can be done without using find_by_sql
>
> Repair has_many :notes
>
> SELECT * FROM repairs
> where exists
> (select * from notes where repairs.id=notes.repair_id
>           and  and notes.flagged)
>

Well at a very basic level you could do Repair.find :all, :conditions
=> "exists (select ...)"
but that doesn''t gain you much.

You could write

Repair.find :all, :select => ''distinct repairs.*'', :joins
=> :notes, :conditions => ["flagged = ?", true]

or something along those lines.

Fred

> Thanks
> Tonypm
> >