Skip to content

Instantly share code, notes, and snippets.

@braindeaf
Created August 8, 2017 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save braindeaf/bceb8244416dc9c7035ad47a76b439b9 to your computer and use it in GitHub Desktop.
Save braindeaf/bceb8244416dc9c7035ad47a76b439b9 to your computer and use it in GitHub Desktop.
Active Record LEFT OUTER JOIN with support for Polymorphic associations
# based on the original Gist from mildmojo
# https://gist.github.com/mildmojo/3724189
#
module ActiveRecord
module LeftJoinExtension
extend ActiveSupport::Concern
module ClassMethods
# Simple left join taking advantage of existing Rails & Arel code
def left_joins(*args)
rel = self.joins(*args).arel
left_joins = rel.join_sources.map do |join|
Arel::Nodes::OuterJoin.new(join.left, join.right)
end
s = self.joins(left_joins)
s.bind_values = rel.bind_values
s
end
# Find records of self where no records of given association exist
def without(assoc_name)
assoc = reflect_on_association(assoc_name)
left_joins(assoc_name).where(assoc.table_name => {assoc.klass.primary_key => nil})
end
end
end
Base.include(LeftJoinExtension)
end
@hassanrehman
Copy link

Had a problem with this, if you use it twice.

Company.left_joins(:users).left_joins(:cities)

will use join on users twice. ANy ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment