# Inner Join with ORM

**URL:** <https://www.ruby-forum.com/t/inner-join-with-orm/208409>\
**Category:** Rails\
**Created:** [June 17, 2011, 10:55am UTC](https://www.ruby-forum.com/t/inner-join-with-orm/208409 "2011-06-17T10:55:20Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![dubstep](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/cdc98d/32.png) [@dubstep](https://www.ruby-forum.com/u/dubstep)\
**Post date:** [June 17, 2011, 10:55am UTC](https://www.ruby-forum.com/t/inner-join-with-orm/208409/1 "2011-06-17T10:55:20Z")

</div>

Hi

I wonder if there is a simple way to do a INNER JOIN with rails instead  
of having to resort to find\_by\_sql and having to write the sql query  
myself?

An example:

I have tasks linked to folders via habtm and tasks are also linked to  
documents via habtm. I now want to see the documents linked to a given  
folder (via its associated tasks)

So in folder.rb I have a function:

def documents  
tids=self.task\_ids.join(",")  
if !tids.blank? then  
return Document.find\_by\_sql(“SELECT distinct documents.\* from  
documents inner join task\_events on documents.id=task\_events.general\_int  
where task\_events.event\_type=‘ATTACH’ and task\_events.task\_id  
in(#{tids})”)  
else  
return []  
end  
end

This works, but there must be a easier way to do this using ORM?

Comments and suggestions most welcome!  
Pieter
