假设我们有这样的数据
< id: 1, name: "Bill", type: "Lemur" >
< id: 2, name: "Bob", type: "Cow" >
< id: 3, name: "Nancy", type: "Lemur" >
< id: 4, name: "Jack", type: "Seagull" >
< id: 5, name: "Jill", type: "Seagull" >
< id: 6, name: "Jake", type: "Cow" >
< id: 7, name: "Jess", type: "Lemur" >
< id: 8, name: "Nick", type: "Lemur" >
< id: 9, name: "Jacky", type: "Cow" >
< id: 10, name: "Jerry", type: "Cow" >
< id: 11, name: "Samuel", type: "Seagull" >
< id: 12, name: "Tessa", type: "Lemur" >我想返回所有的结果,其中类型是Lemur第一,然后返回其余的结果,以任何顺序。我想我可以使用ActiveRecord的分组方法,但是我认为我没有正确地理解它,它正在做其他的事情。在看到另一个堆栈溢出回答后,我尝试过执行Animal.order('Field(type, "Lemur")'),但这也没有起作用。我需要一个亲戚回来,因为我要把这个传给卡米纳里分页。有人知道怎么做吗?
为了使事情变得更复杂,我们实际上想在hstore专栏上这样做,但我想先找出一般的答案。
这是Rails 3.2上的Postgres 9.3。
发布于 2014-10-14 20:53:14
因为Postgres没有像MySQL那样的“按字段订购”(some_column,'Zebra',‘Hipo’)--你可以尝试使用“按砰排序!”,就像这样:
Animal.order("type!='Lemur', type!='Cow', type!='Seagull'")如这一职位所建议的那样:
发布于 2014-10-14 20:50:46
有一种SQL方法可以做到这一点:
Animal.order("CASE animals.type WHEN 'Seagull' THEN 'a' ELSE 'z' END ASC, animals.name ASC")此查询将所有类型为“海鸥”的动物放在第一位,然后根据动物的名称订购其余的动物。
多亏了基本的开关箱 ;)
发布于 2014-10-14 20:47:08
我怀疑你能通过一条一条一组地做这件事。我所能想到的就是这个可能有点不雅:
Lemur.all.concat Animal.all.reject{ | a | a.type == 'Lemur' }编辑:只有当你对数组很满意的时候,这种方式才能奏效。下面是如何使用ActiveRecord::Relation (Where.not(条件)必需的Rails 4)来实现它。
Animal.where(type: 'Lemur') + Animal.where.not(type: 'Lemur')编辑:哎哟,看来后者也会返回一个数组。
https://stackoverflow.com/questions/26369827
复制相似问题