# SELECT, belongs\_to and ActiveRecord

**URL:** <https://www.ruby-forum.com/t/select-belongs-to-and-activerecord/175343>\
**Category:** Rails\
**Created:** [September 11, 2009, 2:31pm UTC](https://www.ruby-forum.com/t/select-belongs-to-and-activerecord/175343 "2009-09-11T14:31:55Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![glex](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/f07891/32.png) [@glex](https://www.ruby-forum.com/u/glex)\
**Post date:** [September 11, 2009, 2:31pm UTC](https://www.ruby-forum.com/t/select-belongs-to-and-activerecord/175343/1 "2009-09-11T14:31:55Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![glex](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/f07891/32.png) [@glex](https://www.ruby-forum.com/u/glex)\
**Post date:** [September 11, 2009, 3:38pm UTC](https://www.ruby-forum.com/t/select-belongs-to-and-activerecord/175343/2 "2009-09-11T15:38:23Z")

</div>

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. 🙂

## Best,

Marnen Laibow-Koser  
[http://www.marnen.org](http://www.marnen.org)  
removed\_email\_address@domain.invalid

---

<div class="post-metadata">

**Author:** ![glex](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/f07891/32.png) [@glex](https://www.ruby-forum.com/u/glex)\
**Post date:** [September 11, 2009, 5:31pm UTC](https://www.ruby-forum.com/t/select-belongs-to-and-activerecord/175343/3 "2009-09-11T17:31:06Z")

</div>

2009/9/11 Gleb M. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> 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
