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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With