Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 917
Rishabh Avatar asked Dec 07 '22 23:12

Rishabh


2 Answers

has_many :comments do
  @object.comments.limit(5)
end
like image 61
Phan Hai Quang Avatar answered Apr 12 '23 23:04

Phan Hai Quang


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
like image 39
nitishmadhukar Avatar answered Apr 12 '23 22:04

nitishmadhukar