Rails/ActiveRecord 按特定值排序 [英] Rails/ActiveRecord sort by particular value

查看:22
本文介绍了Rails/ActiveRecord 按特定值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 3.2 中是否有任何方便的方法通过将具有特定字段的特定值的记录移动到关系的前面来对 ActiveRecord 关系进行排序?例如,如果 MyModel 有一个属性 country,我想对任何查询返回的关系进行排序,其中记录具有 country='Spain' 到关系的前面.

Is there any convenient way in Rails 3.2 to order an ActiveRecord relation by moving records with a particular value for a particular field to the front of the relation? For instance, if MyModel has an attribute country, I would like to sort relations returned by any query with records having country='Spain' to the front of the relation.

推荐答案

类似这样的事情.显然,'name, id' 将取决于您的型号和要求.

Something like this. Obviously 'name, id' would depend on your model and requirements.

MyModel.order("country = 'Spain' DESC, name, id")

这篇关于Rails/ActiveRecord 按特定值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆