Created
August 8, 2017 14:29
-
-
Save braindeaf/bceb8244416dc9c7035ad47a76b439b9 to your computer and use it in GitHub Desktop.
Active Record LEFT OUTER JOIN with support for Polymorphic associations
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
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?