当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - 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?

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: