Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord: keep duplicated objects in .where query

I have an array of ids:

ids = [1, 2, 3, 1]

If I run:

Product.where(id: ids)

I will only get one occurence of the Product having the iD 1. However, I'd like to get as many occurences of the object as there are in the array.

How can I do this ?

like image 374
Graham Slick Avatar asked Mar 31 '26 21:03

Graham Slick


1 Answers

You could load the unique records and then transform the result into an Array with multiple references to each book:

ids = [2109, 2511, 2108, 2109]
tmp_books = Book.find(ids)
new_books = ids.map {|x| tmp_books.detect {|b| b.id == x } }

That produces an array with the duplicates you're looking for while only executing a single query:

Book Load (0.7ms)  SELECT "books".* FROM "books" WHERE "books"."id" IN (2109, 2511, 2108)
=> ["Rick Newman", "Hassan Abbas", "Ms. Martha Byrd", "Rick Newman"]

One consequence of this is that a change to one record in that array could affect other records. So in the example above, there are two references to the Rick Newman book, and so changing the author on the first record would change the author on the last record.

like image 98
Tom Copeland Avatar answered Apr 02 '26 09:04

Tom Copeland