![](/img/trans.png)
[英]Ruby On Rails Active Record - Where Condition AND This Condition or That Condition
[英]Rails Sorting the record based on the array passed in where condition
我想按照我在 array 中傳遞值的順序對我的 where 條件結果進行排序。 我正在做的是我有一個 id 數組
ids = [80, 20, 3, 91, 84, 90, 98, 97, 68, 99, 92, 73]
當我將此數組傳遞給 where 條件時,例如:
products = Product.where(id: ids)
它以不同的順序(隨機順序)返回結果活動記錄關系,例如:
=>[ 20 ,84, 3,98 , .............. ]
(這是活動記錄關系對象,我在這里只提到了 id)
但我希望它以相同的順序返回對象,我正在傳遞類似的值(在活動記錄關系對象中,而不是數組中)
=> [80, 20, 3, 91, 84, 90, 98, 97, 68, 99, 92, 73]
我怎樣才能做到這一點 。
我有這個只需要做的解決方案
在 product.rb 文件中的產品模型中放置:
def self.order_by_ids(ids)
order_by = ["case"]
ids.each_with_index.map do |id, index|
order_by << "WHEN id='#{id}' THEN #{index}"
end
order_by << "end"
order(order_by.join(" "))
end
查詢將是:
products = Product.where(:id => ids).order_by_ids(ids)
這里 ids 將是 id 的數組
只需使用 ids 數組的索引進行排序:
products = Product.where(id: ids).sort_by { |prod| ids.index(prod.id) }
此外,它與數據庫無關,而且可以在 Ruby 中進行,因為在任何情況下都不會有數百萬個 ID。
答案僅適用於 mysql
mysql 中有一個函數叫FIELD()
所以你可以做類似的事情
products = Product.where(id: ids).order("field(id, #{ids.join ','})")
在 Postgres 中
hot_offer_ids = ["7081", "7083", "6917", "5075"]
values = ''
hot_offer_ids.each_with_index do |offer_id, index|
values += ", " if index > 0
values += %((#{offer_id}, #{index}))
end
hot_offers = Offer.joins("join (VALUES #{values}) as x(id, ordering) on offers.id = x.id").order("x.ordering")
您可以使用這個 gem ( order_as_specified ),它允許您像這樣執行本機 SQL 排序:
Model.where(id: ids).order_as_specified(id: ids)
參考答案: 鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.