と の 2 つのタイプが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')
これまでに2つのことを試しました:
配列 (スコープではない) を使用するアプローチ #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
これはうまくいくかもしれませんが、うまくいけば利用可能なスコープマジックを使用して、より良い方法を探しています。