Order nested association in as_json
Asked Answered
D

1

7
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.

Dishman answered 27/2, 2017 at 13:9 Comment(5)
Possible duplicate of Rails render as json, include nested attribute and sortCartilaginous
@Cartilaginous Thanks for your effort, but where do you see as_json in the question you found?Dishman
All the technics listed in that answer works the same way for as_json as well. Just try it out.Cartilaginous
@Cartilaginous Sounds fantastic! Could you please give an example how that could look like, cause I've tried without success?Dishman
You can create a method and call with as_json like user.as_json(methods: : permalink) in this method set your logic in a way, that will give you records with updated_at order.Old
C
3

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)
Cartilaginous answered 27/2, 2017 at 13:48 Comment(1)
Thanks a lot for a working solution! But it's a pity that there doesn't seem to be any inherit way to do this. With the handy helper methods like :only, :ecxept it's a really nice and fast way to sculpt small json objects.Dishman

© 2022 - 2024 — McMap. All rights reserved.