ActiveRecord:将重复的对象保留在.where查询中 [英] ActiveRecord: keep duplicated objects in .where query
问题描述
我有一个id数组:
ids = [1, 2, 3, 1]
如果我运行:
Product.where(id: ids)
我只会发生一次<$ c iD 1
的$ c>产品。
但是,我想获得与数组中一样多的对象出现。
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.
我该怎么做?
推荐答案
您可以加载唯一记录,然后将结果转换为对每本书有多个引用的Array:
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"]
这样做的一个后果是,对该数组中一个记录的更改可能会影响其他记录。因此,在上面的示例中,对Rick Newman的书有两个引用,因此在第一条记录上更改 author
将会更改 author
在最后一条记录上。
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.
这篇关于ActiveRecord:将重复的对象保留在.where查询中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!