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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.