我使用 Ruby on Rail 的查询接口(interface)编写了几个复杂的查询(至少对我来说):
watched_news_posts = Post.joins(:news => :watched).where(:watched => {:user_id => id})
watched_topic_posts = Post.joins(:post_topic_relationships => {:topic => :watched}).where(:watched => {:user_id => id})
这两个查询本身都可以正常工作。两者都返回 Post 对象。我想将这些帖子合并到一个 ActiveRelation 中。由于某个时候可能有数十万个帖子,因此这需要在数据库级别完成。如果它是 MySQL 查询,我可以简单地使用 UNION
运算符。有人知道我是否可以使用 RoR 的查询界面做类似的事情吗?
最佳答案
这是我编写的一个快速小模块,它允许您联合多个作用域。它还将结果作为 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
关于ruby-on-rails - ActiveRecord 查询联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6686920/