Reputation: 13842
I have method
def self.get_ayahs_by_array(ayahs_keys_array)
self.where(ayah_key: ayahs_keys_array)
end
Which does a query on the Quran::Ayah
model. ayahs_keys_array
is an array of keys (primary_key) in a certain order. The query returns a different order, but I want it to return as the same order as the queried array.
Example: ayahs_keys_array
is [5,4,1,2,7]
and I want it to return in THAT order and not [1,2,4,5,7]
Any ideas?
Upvotes: 0
Views: 22
Reputation: 44685
In MySql:
self.where(ayah_key: ayahs_keys_array).order("FIELD(ayah_key, #{ ayahs_keys_array.joins(', ') })")
For postgres is slightly more complicated as you need to build whole CASE statement. Might be easier to do it on the application level:
self.where(ayah_key: ayahs_keys_array).order_by {|r| ayahs_keys_array.index r.ayah_key}
Finally, you can try this gem: https://github.com/panorama-ed/order_as_specified. If you do, please let us know how it went as I never used it.
Upvotes: 1