Reputation: 249
I have posts that are associated with comments. I want to create an array of comments from the first 10 posts. I had the following method but to_a seems to not work anymore? Also will this give an N+1 query? should I do includes(:comments)
to preload them?
def 10_posts_comments
posts = Post.limit(10)
posts.flat_map do |post|
post.comments.to_a
end
end
I'm still new at this so any help appreciated.
Upvotes: 0
Views: 95
Reputation: 331
Can you try:
def latest_comments
Post.includes(:comments).last(10).map(&:comments).flatten
end
Upvotes: 0
Reputation: 1276
You can try this
def 10_posts_comments
Comment.where(post: Post.limit(10)).to_a
end
Upvotes: 1