这是我编写的一个快速小模块,它允许您UNION多个范围。它还将结果作为ActiveRecord :: Relation的实例返回。
module ActiveRecord::UnionScope
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def union_scope(*scopes)
id_column = "#{table_name}.id"
sub_query = scopes.map { |s| s.select(id_column).to_sql }.join(" UNION ")
where "#{id_column} IN (#{sub_query})"
end
end
end
这是要点:https : //gist.github.com/tlowrimore/5162327
编辑:
根据要求,以下是UnionScope的工作方式示例:
class Property < ActiveRecord::Base
include ActiveRecord::UnionScope
# some silly, contrived scopes
scope :active_nearby, -> { where(active: true).where('distance <= 25') }
scope :inactive_distant, -> { where(active: false).where('distance >= 200') }
# A union of the aforementioned scopes
scope :active_near_and_inactive_distant, -> { union_scope(active_nearby, inactive_distant) }
end
Post.watched_news_posts.watched_topic_posts
。您可能需要将参数发送到范围,例如:user_id
和:topic
。