Rishabh
Rishabh

Reputation: 103

In active-model-serializers, how to limit the associated objects returned from a has_many association?

So I have

    render json: Post.all       

This returns all my Posts and in my Post serializer I have

    class PostSerializer < ActiveModel::Serializer
      has_many :comments
    end        

I want the number of comments returned in the JSON to be limited to 5 and have a variable which tells if more comments are there. Is this possible?

Edit: I think I'll manage the more part with a new call. But can't figure out how to limit the comments in the serializer

Upvotes: 5

Views: 4622

Answers (3)

nitishmadhukar
nitishmadhukar

Reputation: 236

In your comments model write a scope method to limit the number of comments.

In models/comment.rb

scope :limited_comments, lambda { limit(5) }

In PostSerializer

has_many :comments

def comments
  Comment.limited_comments
end

Upvotes: 5

Phan Hai Quang
Phan Hai Quang

Reputation: 777

has_many :comments do
  @object.comments.limit(5)
end

Upvotes: 11

mparkitny
mparkitny

Reputation: 1195

I afraid that there isn't any way to limit amount of returned records in the serializer. However you can limit your records in controller with below lines.

# This code returns last 5 posts    
posts = Post.last(5)

render json: posts

Did you think about implementing some kind of pagination feature here?

Upvotes: 0

Related Questions