How to sort Rails Active Model serializers' response

Justin D. picture Justin D. · Aug 10, 2013 · Viewed 8.4k times · Source

Weirdly, I haven't find anything on the subject...

How can I sort the JSON my Rails server delivers? I am currently using ActiveModel Serializer :

 embed :ids, include: true
 attributes :id, :name

 has_many :places

I would like to sort the embedded places.

The only answer I found is this SO question, but it explains how the serializer sort by default, instead of how I can sort.

Answer

wedens picture wedens · Aug 11, 2013

You can define it as property and handle sorting. E.g:

def places
    object.places.order("title")
end

https://github.com/rails-api/active_model_serializers#associations