Created
September 8, 2017 14:12
-
-
Save seguelador/494c4d5e989f42d8f4a91b3da2108216 to your computer and use it in GitHub Desktop.
Active Record Union Scopes
This file contains 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
# from https://stackoverflow.com/questions/6686920/activerecord-query-union | |
# lib/active_record_extension.rb | |
module ActiveRecordExtension | |
extend ActiveSupport::Concern | |
class_methods do | |
def union_scope(*scopes) | |
id_column = "#{table_name}.#{primary_key}" | |
sub_query = scopes.map { |s| s.select(id_column).to_sql }.join(" UNION ") | |
where "#{id_column} IN (#{sub_query})" | |
end | |
end | |
ActiveRecord::Base.send(:include, ActiveRecordExtension) | |
end |
This file contains 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
# from https://stackoverflow.com/questions/6686920/activerecord-query-union | |
# config/initializers/extensions.rb | |
require "active_record_extension" |
This file contains 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
# from https://stackoverflow.com/questions/6686920/activerecord-query-union | |
# example in some model | |
scope :active_nearby, -> { where(active: true).where('distance <= 25') } | |
scope :inactive_distant, -> { where(active: false).where('distance >= 200') } | |
scope :active_near_and_inactive_distant, -> { union_scope(active_nearby, inactive_distant) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Less problems and easier to follow: