Search code examples
ruby-on-railspostgresqlactiverecordhstore

How to return matched results in ActiveRecord and then remainder?


Say we have data like

< 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" >

I want to return all results where type is Lemur first and then return the rest of the results in any order. I thought I could use the group method of ActiveRecord but I don't think I understood that correctly and it's doing something else. I've tried doing Animal.order('Field(type, "Lemur")') after seeing another Stack Overflow answer but that didn't work either. I need a relation returned as I'm going to pass this on to Kaminari to paginate. Anyone know how to do this?

To make things more complicated we actually want to do this on an hstore column but I wanted to figure out the general answer first.

This is on Rails 3.2 with Postgres 9.3.


Solution

  • Since Postgres doesn't have an "ORDER BY FIELD(some_column, 'Zebra', 'Hipo')" like MySQL does - you could try to use "Order by bang!", like such:

    Animal.order("type!='Lemur', type!='Cow', type!='Seagull'")
    

    As suggested on this post:

    Simulating MySQL's ORDER BY FIELD() in Postgresql