Eager loading association but limit return

痞子三分冷 提交于 2019-12-05 11:08:14

This isn't something that you can do with raw SQL as LIMIT's are on the total dataset size, not anything else.

The only way of doing this purely by SQL is to create a fake id column in your join and filter than when it comes out which is something that implementation wise is incredibly dependant on the database server you are using.

The alternatives as either get all categories and posts and cut the recordset down, or get all categories and iteratively get 10 posts as Joerg suggests.

Do you need to retrieve them all in one SQL statement? Or is it ok to lazy load them when you need them?

In which case

Category.all

will get all your categories, and stepping through them to get your posts could simply be

Category.all.each do |category|
  category.posts.limit(10)
end

Would this not be enough?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!