Lorenzo Rapetti
Lorenzo Rapetti

Reputation: 96

Ruby on Rails as_json limit

I have this "as_json" method in my Post model:

def as_json(options={})
    super(options.merge(:include => { :comments => { :include => [:user] }, :hashtags => {}, :user => {}, :group => {} }))
end

I'd like to set a limit attribute in :comments like this:

def as_json(options={})
    super(options.merge(:include => { :comments => { :include => [:user], :limit => 10 }, :hashtags => {}, :user => {}, :group => {} }))
end

but it doesn't work.

How should I proceed?

Upvotes: 1

Views: 462

Answers (1)

MatayoshiMariano
MatayoshiMariano

Reputation: 2106

I think that you have only one possibility.

I suppouse that you have a has_many :comments association in your Post model

So you can define the next has_many association in your Post model, something like this:

has_many :ten_comments, -> { limit(10) }, class_name: "Comment", foreign_key: :post_id

And then you will be able to do this in the as_json method:

def as_json(options={})
   super(options.merge(:include => { :ten_comments => { :include => [:user] }, :hashtags => {}, :user => {}, :group => {} }))
end

Sorry for posting four years later, but I hope that someone find useful your question and this answer.

Upvotes: 1

Related Questions