SELECT, belongs_to and ActiveRecord

def A
belongs_to B
belongs_to C
end

I want to select all the A where a.b.name LIKE “x” and a.c.name LIKE Y.
Is it possible to do this with one SQL statement?

Gleb M. wrote:

def A
belongs_to B
belongs_to C
end

I want to select all the A where a.b.name LIKE “x” and a.c.name LIKE Y.
Is it possible to do this with one SQL statement?

Sure:

SELECT * from a
LEFT JOIN b ON b.id = a.b_id
LEFT JOIN c ON c.id = a.c_id
WHERE b.name LIKE ‘X’ – did you mean ‘%X%’?
AND c.name LIKE ‘Y’

Writing a suitable ActiveRecord find statement is left as an exercise to
the student. :slight_smile:

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

2009/9/11 Gleb M. [email protected]:

def A
 belongs_to B
 belongs_to C
end

I want to select all the A where a.b.name LIKE “x” and a.c.name LIKE Y.
Is it possible to do this with one SQL statement?

Why do you want to use sql? Let rails do it for you, something like
find(:all, :include => [:b, :c], :conditions => [b.name like ? and c.name like ?, ‘x’, ‘y’] )

Colin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs