1

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?
steve hype
  • 38
  • 6

1 Answers1

0

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 :)

Harsh Trivedi
  • 1,594
  • 14
  • 27
  • thank so much for this. Is this considered an N+1 query? – steve hype Jul 16 '16 at 19:14
  • Am very glad that it helped. I don't think this is N+1 query. N+1 queries occur when there is a 1-many relationship. Wait a moment, I will try to find good example. – Harsh Trivedi Jul 16 '16 at 19:18
  • The accepted answer of this question: http://stackoverflow.com/questions/97197/what-is-the-n1-selects-issue demonstrates N+1 queries pretty well with car and its wheels example. – Harsh Trivedi Jul 16 '16 at 19:19
  • Well, having one more look. Even though there is not 1-many relationship. This seems N+1 now. Because 1 query for getting `@books` and N queries then to get them in correct order. But I am not an expert on this subject to comment if it qualifies as N+1 or not. – Harsh Trivedi Jul 16 '16 at 19:23