【发布时间】:2015-08-19 17:55:41
【问题描述】:
我有两种类型: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
这可能有效,但我正在寻找更好的方法,希望能使用一些可用的范围魔法。
【问题讨论】:
-
所以没有赏金给我? :S
-
对不起,没有意识到 - 认为接受的答案会自动获得赏金。现已授予。
标签: ruby-on-rails scope rails-activerecord acts-as-tree