【发布时间】:2019-08-15 09:14:16
【问题描述】:
所以我从数据库中得到了这个对象数组,我必须按顺序对其进行排序:
- 按分数(反向)
- 按计数(反向)
- 按名称
我已经尝试了所有三个反向但我需要的是最后一个不应该是反向 (DESC) 这是我的代码:
new_data = data.sort_by{ |t| [t.score, t.matches_count, t.name] }.reverse
结果
[
{
"id": null,
"team_id": 939,
"name": "DAV",
"matches_count": 2,
"score": 100.0
},
{
"id": null,
"team_id": 964,
"name": "SAN",
"matches_count": 1,
"score": 100.0
},
{
"id": null,
"team_id": 955,
"name": "PAS",
"matches_count": 1,
"score": 100.0
},
{
"id": null,
"team_id": 954,
"name": "PAR",
"matches_count": 1,
"score": 100.0
},
{
"id": null,
"team_id": 952,
"name": "NUE",
"matches_count": 1,
"score": 100.0
}
]
预期结果应该按名称按 ASC 顺序而不是 DESC 我知道我的代码是错误的,因为 t.name 在 .reverse 内,但是如果我在前 2 个之后单独按 name 重新排序它,我会得到错误的答案它只会按名称而不是按 3 排序。我也尝试从查询中使用.order("name DESC"),所以当反向它会去 ASC 但没有运气。谢谢!
【问题讨论】:
-
@noname 是的,我已经尝试过,正如您在问题的最后一部分中看到的那样,它将仅按名称返回数据,而不是按(先得分,然后匹配然后名称)。谢谢!
-
我刚注意到,所以我删除了评论。
标签: ruby-on-rails ruby api ruby-on-rails-5