Skip to content

Instantly share code, notes, and snippets.

@hassanrehman
Created March 26, 2018 17:06
Show Gist options
  • Save hassanrehman/57773ecfda0e170f67b4f10c9ccceb92 to your computer and use it in GitHub Desktop.
Save hassanrehman/57773ecfda0e170f67b4f10c9ccceb92 to your computer and use it in GitHub Desktop.
Ability to use left_joins with ActiveRecord
module ActiveRecord
module QueryMethods
#keeping track of left joins sent
attr_accessor :left_joins_values
#photocopy of joins except for the variable that records left_joins separate from the joins
def left_joins(*args)
return self if args.compact.blank?
relation = clone
args.flatten!
relation.left_joins_values ||= []
relation.left_joins_values += args
relation
end
alias_method :original_build_joins, :build_joins
def build_joins(manager, joins)
#build original
original_build_joins(manager, joins)
#add left joins .. considering only the ones with associations
association_joins, other_joins = (left_joins_values||[]).partition{|join| join.is_a?(Hash) or join.is_a?(Symbol) or join.is_a?(Array) }
#for any other kind of join, use it the same way
original_build_joins(manager, other_joins) unless other_joins.empty?
#association ones .. use join_type OuterJoin to create the associative join
unless association_joins.empty?
join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, association_joins, [])
join_dependency.join_associations.each do |association|
association.join_type = Arel::OuterJoin
association.join_to(manager)
end
end
manager
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment