Rails 4 Eager load limit subquery -
is there way avoid n+1 problem when eager loading , applying limit subquery? want avoid lots of sql queries this:
category.all.each |category| category.posts.limit(10) end
but want 10 posts per category, standard eager loading, gets posts, not suffice:
category.includes(:posts).all
what best way solve problem? n+1 way limit amount of posts per category?
from rails docs
if eager load association specified :limit option, ignored, returning associated objects
so given following model definition
class category < activerecord::base has_many :posts has_many :included_posts, -> { limit 10 }, class_name: "post" end
calling category.find(1).included_posts
work expected , apply limit of 10 in query. however, if try category.includes(:included_posts).all
limit
option ignored. can see why case if @ sql generated eager load
category.includes(:posts).all category load (0.2ms) select "categories".* "categories" post load (0.4ms) select "posts".* "posts" "posts"."category_id" in (1, 2, 3)
if added limit
clause posts query, return total of 10 posts , not 10 posts per category might expect.
getting problem, eager load posts , limit loaded collection using first(10)
categories = category.includes(:posts).all categories.first.posts.first(10)
although you're loading more models memory, bound more performant since you're making 2 calls against database vs. n+1. cheers.
Comments
Post a Comment