John Beynon
John Beynon

Reputation: 37507

Eager loading association but limit return

It seems like a simple query but I just can't nail it.

Basically it boils down to the age old concept of a categories having posts. The expected associations are in place, a category has_many posts whilst a post belongs to a category.

I want to retrieve all the categories with their posts but limit the number of posts to 10.

Any ideas?

Upvotes: 5

Views: 799

Answers (2)

Neil Middleton
Neil Middleton

Reputation: 22240

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.

Upvotes: 1

Joerg
Joerg

Reputation: 3823

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?

Upvotes: 0

Related Questions