Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort Rails Active Model serializers' response

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.

like image 273
Justin D. Avatar asked Aug 10 '13 21:08

Justin D.


2 Answers

I prefer this way

has_many :person_medals do
  object.places.order(:title)
end
like image 158
Kiry Meas Avatar answered Sep 24 '22 19:09

Kiry Meas


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

like image 39
wedens Avatar answered Sep 25 '22 19:09

wedens