2

我有两种类型:blogsposts. Post 使用closure_tree gem(一个acts_as_tree变体)来允许帖子嵌套在帖子下。此外,每个博客has_many帖子。

class Post < ActiveRecord::Base
  acts_as_tree
end

给定一组博客(例如,由同一作者撰写),我想将这些博客中的所有帖子作为一个范围(即,作为 ActiveRecord::Relation 而不是作为数组)。

就像是:

Blog.all_posts_by('john')

到目前为止,我已经尝试了两件事:

方法#1,使用数组(不是范围),如下:

class Blog
  has_many :posts
  def self.all_posts_by author_name
    self.where(author_name: author_name).map(&:posts).flatten.map(&:self_and_descendants).flatten
  end
end

但我想要一个范围,因为数组映射方法可能无法很好地处理大型数据集。

方法#2:这种方法产生一个真实的范围,但使用 sql 联合和 sql 字符串:

class Blog
  has_many :posts
  def self.all_posts_by author_name 
    post_collections = []
    Blog.where(author_name: author_name).each do |blog|
      post_collections = blog.posts.map(&:self_and_descendants)
    end
    posts_sql = ""
    post_collections.each do |post_collection|
      posts_sql << "( #{post_collection.to_sql} ) union "
    end
    final_sql = posts_sql.chomp('union ')
    result = Post.from("
        (
            #{final_sql}
        ) #{Post.table_name}
    ").distinct
  end
end

这可能有效,但我正在寻找一种更好的方法,希望使用一些可用的范围魔法。

4

1 回答 1

2

如果您也将 存储blog_id在嵌套帖子上,而不仅仅是在根级别帖子上,您可以执行以下操作并且不需要查询后代:

class Blog
  has_many :posts
  def self.all_posts_by author_name
    self.where(author_name: author_name).includes(:posts).map(&:posts).flatten
  end
end

语句 eager 从数据库中加载所有帖子,这includes比顺序加载要快得多。http://www.spritle.com/blogs/2011/03/17/eager-loading-and-lazy-loading-in-rails-activerecord/

更新:

如果您想将它们作为范围返回,我认为最好在Post模型上实际使用它,因为这更有意义:

class Post
  belongs_to :blog

  def self.all_by author_name
    self.joins(:blog).where(blog: [name: author_name])
  end 
end

请注意,这仅在您在所有嵌套帖子上设置 blog_id 时才有效。

如果它真的是一个高性能应用程序,我还建议您使用像 elasticsearch 这样的搜索索引引擎,因为它在这种类型的场景中表现非常好,即使您没有任何搜索字符串。这将允许您构建更多这样的过滤器并将它们组合起来,但它也会给应用程序基础架构带来更多复杂性。

于 2015-08-23T20:55:29.900 回答