0

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?

2
  • You can use scope to customize the order of a query. Commented Oct 11, 2015 at 22:10
  • What database do you use? Commented Oct 11, 2015 at 22:26

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I ended up doing something like this too .sort{|e1, e2| ayahs_keys_array.index(e1.ayah_key) <=> ayahs_keys_array.index(e2.ayah_key)} because order_by throws an error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.