Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order nested association in as_json

class User
  has_many :posts
end

I want to render a json hash with the as_json method.

How would I order the posts in the code below by their updated_at attribute without setting a default order on the association?

user.as_json(include: {posts: {include: :comments})

This will not be used as a request response and I'd like to avoid setting a default sorting on the association.

like image 756
Fellow Stranger Avatar asked Feb 27 '17 13:02

Fellow Stranger


1 Answers

Instead of scope you may use custom method:

class User < ApplicationRecord
  has_many :posts

  def updated_posts
    posts.order("posts.updated_at").as_json(include: :comments)
  end
end

user.as_json(methods: :updated_posts)

This will produce something like this:

{
  # user attributes
  "updated_posts => [
    # posts with comments
  ]
}

If you wish that posts to be strictly under the posts key, you may do the following:

json = user.as_json(methods: :updated_posts)
json[:posts] = json.delete(:updated_posts)
like image 187
Slava.K Avatar answered Nov 09 '22 22:11

Slava.K