13

奇怪的是,我没有找到任何关于这个主题的东西......

如何对 Rails 服务器提供的 JSON 进行排序?我目前正在使用 ActiveModel 序列化器:

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

 has_many :places

我想对嵌入的places.

我找到的唯一答案是这个 SO question,但它解释了序列化程序默认如何排序,而不是我如何排序。

4

2 回答 2

22

您可以将其定义为属性并处理排序。例如:

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

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

于 2013-08-11T06:47:46.240 回答
2

我更喜欢这种方式

has_many :person_medals do
  object.places.order(:title)
end
于 2020-09-21T17:17:59.793 回答