Last active
September 29, 2016 20:00
-
-
Save njakobsen/6395146 to your computer and use it in GitHub Desktop.
Poor man's outer join for rails. Just extend ActiveRecord::Base with this beauty, and voila! MyModel.outer_joins(:some_association).ftw!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module OuterJoins | |
def outer_joins(*associations) | |
pattern = / (?:INNER )?JOIN /i | |
scope = all | |
associations.each do |association| | |
inner_join_sql = scope.unscoped.joins(association).to_sql | |
outer_join_sql = inner_join_sql.gsub(pattern, ' LEFT OUTER JOIN ') | |
scope = scope.joins(outer_join_sql[/LEFT OUTER JOIN .+/]) | |
end | |
return scope | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment