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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With