我有两种类型:blogs
和posts
. 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
这可能有效,但我正在寻找一种更好的方法,希望使用一些可用的范围魔法。