ruby-on-rails - ActiveRecord 查询联合

标签 ruby-on-rails activerecord union active-relation

我使用 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/

相关文章:

mysql - 遍历记录并将其存储到数组中

ruby-on-rails - Rspec - 测试方法在另一个方法内收到调用

sql - 与 Ruby on Rails 中的首次性能对比

mysql - 从两个 MySQL 表中选择并分组

mysql - 多次 Union 和 Join 操作后求和列

ruby-on-rails - 关闭 Firefox 中文本字段的自动完成功能

ruby-on-rails - 如何使用Factory Girl生成回形针附件?

ruby-on-rails - 让 Rails #destroy_all 运行得更快

ruby-on-rails - rails 找到帖子的 user_id = user 的所有评论

php - SQL LEFT JOIN 不使用主键的查询太慢,如何加快速度?