0

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.

2 Answers 2

1

You can try this

def 10_posts_comments     
  Comment.where(post: Post.limit(10)).to_a
end
Sign up to request clarification or add additional context in comments.

Comments

0

Can you try:

def latest_comments
  Post.includes(:comments).last(10).map(&:comments).flatten
end

1 Comment

You can use your method, I just changed the name since it bothered me the leading 10. Sorry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.