Ruby on rails 按选择顺序排序
这应该是一个简单的问题,但我似乎找不到一个好的解决办法。我有一个用户正在选择的id列表,我想为FOO保留该顺序Ruby on rails 按选择顺序排序,ruby-on-rails,sorting,Ruby On Rails,Sorting,这应该是一个简单的问题,但我似乎找不到一个好的解决办法。我有一个用户正在选择的id列表,我想为FOO保留该顺序 foo_ids = [1899, 7, 1, 2, 3, 42] foos = Foo.find(foo_ids) 关于如何在返回结果集后保留select上的顺序,或者使用result,您有什么想法吗?我认为使用ActiveRecord没有办法做到这一点 然而,以下是我要做的: people_ids = [1899, 7, 2, 3, 42] people = Person.un
foo_ids = [1899, 7, 1, 2, 3, 42]
foos = Foo.find(foo_ids)
关于如何在返回结果集后保留select上的顺序,或者使用result,您有什么想法吗?我认为使用ActiveRecord没有办法做到这一点 然而,以下是我要做的:
people_ids = [1899, 7, 2, 3, 42]
people = Person.unscoped.find(people_ids)
people_ids.each_with_object(result = []) do |id, result|
result << people.detect { person.id == id }
end
result # => what you are looking for
people\u id=[1899,7,2,3,42]
people=Person.unscoped.find(people\u id)
人员id。每个带有_对象(result=[])的| id,result|
结果你在寻找什么
我使用Person.unscoped,因为在任何情况下,您的默认范围都不是您想要的范围。所以它可能会快一点(非常快一点)
使用find(people\u id)只生成一个查询,不管people\u id有多大。
最糟糕的情况是这样做:
people_ids.each_with_object(result = []) do |id, result|
result << Person.find(id)
end
people_id。每个带有_对象(result=[])的_都有| id,result|
结果我认为没有办法用ActiveRecord做到这一点
然而,以下是我要做的:
people_ids = [1899, 7, 2, 3, 42]
people = Person.unscoped.find(people_ids)
people_ids.each_with_object(result = []) do |id, result|
result << people.detect { person.id == id }
end
result # => what you are looking for
people\u id=[1899,7,2,3,42]
people=Person.unscoped.find(people\u id)
人员id。每个带有_对象(result=[])的| id,result|
结果你在寻找什么
我使用Person.unscoped,因为在任何情况下,您的默认范围都不是您想要的范围。所以它可能会快一点(非常快一点)
使用find(people\u id)只生成一个查询,不管people\u id有多大。
最糟糕的情况是这样做:
people_ids.each_with_object(result = []) do |id, result|
result << Person.find(id)
end
people_id。每个带有_对象(result=[])的_都有| id,result|
结果谢谢你的回复,德尔巴,我一定会给w旋转,谢谢你的输入!谢谢,这大概就是解决方案。我稍微调整了一下,但我相信这也会起作用。谢谢你的回复,德尔巴,我一定会给你一个w旋转,谢谢你的输入!谢谢,这大概就是解决方案。我稍微调整了一下,但我相信这也会起作用。