Skip to content

Instantly share code, notes, and snippets.

@mbobin
Forked from ozydingo/active_record_extension.rb
Last active September 12, 2016 12:50
Show Gist options
  • Select an option

  • Save mbobin/52298a7e3e70bb4a7ecc7a78548b4465 to your computer and use it in GitHub Desktop.

Select an option

Save mbobin/52298a7e3e70bb4a7ecc7a78548b4465 to your computer and use it in GitHub Desktop.
ActiveRecord left join
module ActiveRecordExtension
extend ActiveSupport::Concern
module ClassMethods
# Simple left join taking advantage of existing Rails & Arel code
def left_joins(*args)
inner_joins = self.unscoped.joins(*args).arel.join_sources
left_joins = inner_joins.map do |join|
Arel::Nodes::OuterJoin.new(join.left, join.right)
end
self.joins(left_joins)
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
ActiveRecord::Base.send(:include, ActiveRecordExtension)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment