0

Is it possible to construct a scope like this

User.where(:id => [5,4,3,2,7,1000] )

in a way, that

a) the results are in the order of the ids passed. (This is the simple part, since you can just load the records, and sort the result accordingly)

b) the result is not an array but a scope in itself (The tricky part ;)

Update: Solutions that only work on MySQL are welcome.

flitzwald
  • 20,200
  • 2
  • 32
  • 28

2 Answers2

1

I can think of two ways to do it:

(1) Put an order column in the database.

(2) Use raw SQL and a custom ORDER BY clause like so:

order by (
    case id
    when 5 then 0 
    when 4 then 1
    when 3 then 2
    when 2 then 3
    when 7 then 4
    when 1000 then 5
    end
)

I'm not sure how portable that is.

Mark Thomas
  • 37,131
  • 11
  • 74
  • 101
0

Different databases hold their data in different way, so that noone can surely answer which way it will be ranged.

But if you really challenging this problem why don't use raw SQL, select each tuple and merge it with union while constructing a long SQL-query.

Ivan Shamatov
  • 1,406
  • 1
  • 10
  • 17