# Straight join in rails

**URL:** <https://www.ruby-forum.com/t/straight-join-in-rails/122546>\
**Category:** Rails\
**Created:** [December 9, 2007, 5:58am UTC](https://www.ruby-forum.com/t/straight-join-in-rails/122546 "2007-12-09T05:58:13Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Esad\_H](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/3da27b/32.png) [@Esad\_H](https://www.ruby-forum.com/u/Esad_H)\
**Post date:** [December 9, 2007, 5:58am UTC](https://www.ruby-forum.com/t/straight-join-in-rails/122546/1 "2007-12-09T05:58:13Z")

</div>

Maybe someone will find this useful:

I have a relatively complex (My)SQL query that results from having many  
many :conditions and :includes, and MySQL seems to apply a wrong join  
order so I wanted to force an order using the STRAIGHT\_JOIN statement,  
but rails doesn’t really let you do it. Having to construct this query  
manually (there are 4 joins) and still have a right format for eager  
association loading wasn’t really an option.

I digged into ActiveRecord and modifying the JoinDependency class to  
output "STRAIGHT\_JOIN"s instead of "LEFT OUTER JOIN"s looked like too  
much work too, so I decided to take a shorter route: intercept the  
generated sql query, and replace SELECT with SELECT STRAIGHT\_JOIN.

Here’s a monkey-patch (written against ActiveRecord 1.5.14) that  
achieves this behaviour:

module ActiveRecord  
class Base  
class \<\< self  
VALID\_FIND\_OPTIONS \<\< :straight\_join  
alias\_method :orig\_add\_joins!, :add\_joins!  
def add\_joins!(sql, options, scope = :auto)  
orig\_add\_joins!(sql,options,scope)  
sql.gsub!(/^SELECT/,‘SELECT STRAIGHT\_JOIN’) if  
options[:straight\_join]  
end  
end  
end  
end

So simply supply a :straight\_join =\> true option to finder and it will  
result in a SELECT STRAIGHT\_JOIN … query.
