Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement sorting with Active Model Serializer?

What I would like to do is pass a list of columns to sort by as a sport parameter and have AMS sort the response based on those parameters. For Example if I use this url _GET /authors?sort=lastname,firstname_ it would sport by lastname then firstname. However if I did this GET /authors?sort=number_of_books,lastname,firstnam* it would return authors based on the number of books, then lastname and firstname.

It appears AMS does not do this by default (and they are not going to do it in the future), but can I do something in the serializer that will do this for me?

like image 922
Caleb Sayre Avatar asked Nov 27 '25 13:11

Caleb Sayre


1 Answers

In my experience AMS doesn't really concern itself with sorting. This seems like something you'd do before serializing. Perhaps in the controller or better yet in the model.

UPDATE

@CalebSayre if your sort parameter is just a simple list of fields to sort by you could probably get away with something as simple as this.

render json: Author.order(params[:sort]), serializer: AuthorSerializer

If no sort params are passed in it'll just skip the order clause.

like image 146
Dan Avatar answered Nov 30 '25 02:11

Dan