steve hype steve hype - 4 months ago 15
Ruby Question

Rails where query order by index of array

I'm trying to figure out a way I can order the following query by index in that array...

@books_sorted.map(&:id) => ["31f1d544-4ce5-4bcd-89fd-8a76e4c052fe",
"1ccaab81-9443-40b6-9f0e-06b799377d9e",
"622ebbdf-4eb9-4b2e-879a-5d93c0bdfb29",
"1e255968-6094-4bdb-90de-9c0922a0ad4e",
"14d08406-3136-48e4-84c9-314a652ccf34"]

@books = @books.where("books.id in (?)", @books_sorted.map(&:id)) if @books_sorted.any?

Answer

This should work.

@books_sorted.collect {|book| @books.detect{|x| x.id == book.id}} if @books_sorted.any?

Please note: This isn't a efficient solution, since we are doing the sort in ruby instead of database query. Hope it helps :)