2016-07-07 40 views

回答

0

这将每个ID要做到这一点,最好的方法是使用CASE语句(Postgres的)匹配到产品

ids.map{ |id| Product.find(id) }

+0

这样做的每一个元素查询ids数组,这是你真的不想要的东西英寸 –

0

def order_by_id(ids) 
    order_by = ["case"] 
    ids.each_with_index.map do |id, index| 
    order_by << "WHEN id=#{ActiveRecord::Base.connection.quote id} THEN #{index}" 
    end 
    order_by << "end" 
    order(order_by.join(" ")) 
end 

这应该让你在那里获得最大的成功。

+0

使用字符串插值构建SQL查询是对SQL注入攻击的邀请。使用Rails的内置参数绑定。 –

+0

@Jordan绝对。这使我们成为了那里的一部分,并不是一个完整的解决方案。我会更新。 – jstoup111

0

试试这个:

ids = [5,2,1,6] 
records = Product.find(ids).index_by(&:id).values_at(*ids)