ActiveRecord: keep duplicated objects in .where query

女生的网名这么多〃 提交于 2020-01-04 10:22:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!