Andres
Andres

Reputation: 1506

How can I limit the number of records included in an association within a response?

I am sending back a json object in the following way:

respond_with @authors, include: :posts

I need to limit the number of posts. I tried with:

respond_with @authors, include: :posts, limit: 10

but it's not working.

Upvotes: 0

Views: 72

Answers (1)

user419017
user419017

Reputation:

What I'd do here is create a relationship for latest_posts:

class Author
  has_many :latest_posts, -> { limit(10) }, class_name: Post
end

# usage

respond_with @authors, include: :latest_posts

Upvotes: 2

Related Questions