DEV Community


Discussion on: Rails N + 2 queries

brunvez profile image
Bruno Vezoli Author

Yeah, you can always do the queries straight somewhere else, but that wouldn't help you preload the records. The example was very simple I hope it doesn't miss the point, which is preloading and not doing extra queries and not just being able to get the data. Maybe something like this paints a clearer picture:

posts = Post.all.includes(:comments) do |post|
  create_thumbnail(post, post.uncensored_comments)

This creates the same N + 2 queries as before since the .includes(:comments) it's actually useless here. Sure you can always find a way around not having associations in the model, one of the ways to do so and that I didn't mention in the post is to do the following:

posts = Post.all
uncensored_comments = Comment.where(post: posts, uncensored: false).group_by(&:post_id) do |post|
  create_thumbnail(post, uncensored_comments[])

But that, IMO, it's very ugly and does not follow OOP at all.