问题
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 ?
回答1:
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.
回答2:
You can try like this, as where clause return the array of record:
ids = [1, 2, 3, 1]
products = []
ids.each do |id|
products << Product.find(id)
end
来源:https://stackoverflow.com/questions/48489103/activerecord-keep-duplicated-objects-in-where-query