Skip to content

Instantly share code, notes, and snippets.

@njakobsen
Last active September 29, 2016 20:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save njakobsen/6395146 to your computer and use it in GitHub Desktop.
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!
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