13

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.

Community
  • 1
  • 1
Justin D.
  • 4,946
  • 5
  • 36
  • 69

2 Answers2

22

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

wedens
  • 1,782
  • 14
  • 18
  • I marked your answer as accepted because you provided me with a better keyword : `order`. I was searching for `sort` and got absolutely no result, but with `order`, I got this SO question (http://stackoverflow.com/questions/6972406/rails-render-as-json-include-nested-attribute-and-sort) which explains other methods to do what i wanted to - yours works like a charm too. – Justin D. Aug 13 '13 at 13:35
  • 4
    Quick note, if your child object also goes through a serialiser this will break that, and revert to using as_json – James Pearson Feb 15 '16 at 12:41
  • 1
    Weird that it doesn't have the same DSL as model associations, where you can just put the order there. – Petercopter Dec 07 '16 at 06:51
  • 3
    Is there a way to achieve this without adding an N+1 query? – Nigel Sheridan-Smith May 29 '17 at 03:22
  • 7
    I added this to the model's `has_many`: `has_many :images, ->{ order(position: :asc) }, class_name: "PropertyImage"` – Nigel Sheridan-Smith May 29 '17 at 03:26
  • Is there a way to sort by `:name`? – stackjlei Oct 30 '17 at 21:31
4

I prefer this way

has_many :person_medals do
  object.places.order(:title)
end
Kiry Meas
  • 1,200
  • 13
  • 26
  • 1
    This is nice. Cleaner and also addresses the issue commented by @FearMediocrity on the accepted answer - if the child object also goes through a serializer, your order will still stick. – bitfidget Mar 15 '21 at 01:31