gpt4 book ai didi

ruby-on-rails - 根据数组对对象列表进行排序 (Rails)

转载 作者:行者123 更新时间:2023-12-02 04:02:02 25 4
gpt4 key购买 nike

如果 id 来自表,我有一个数组,例如:

b = [659, 658, 656, 645, 644, 657, 634, 643, 649, 650, 651, 636, 633, 607, 605, 604, 648, 647, 675, 674, 667, 499]

我用它从 tat 表中检索对象列表:

k = Photo.where(id:b)

我得到的是一个对象列表,这些对象的排序顺序与数组的顺序不同。

我怎样才能做到这一点?

最佳答案

如果 id 是唯一的

您可以使用index_byvalues_at :

k = Photo.where(id: b).index_by(&:id).values_at(*b)

示例:

b = [5,3,1]
Country.where(id: b)
#=> [#<Country id: 1, name: "France">, #<Country id: 3, name: "Ukraine">, #<Country id: 5, name: "Spain">]
Country.where(id: b).index_by(&:id)
#=> {1=>#<Country id: 1, name: "France">, 3=>#<Country id: 3, name: "Ukraine">, 5=>#<Country id: 5, name: "Spain">}
Country.where(id: b).index_by(&:id).values_at(*b)
#=> [#<Country id: 5, name: "Spain">, #<Country id: 3, name: "Ukraine">, #<Country id: 1, name: "France">]

如果 b 包含重复的 id

使用b = [5,3,3,1],第一个方法将输出:

#=> [#<Country id: 5, name: "Spain">, #<Country id: 3, name: "Ukraine">, #<Country id: 3, name: "Ukraine">, #<Country id: 1, name: "France">]

您可以使用index_byslice :

k = Photo.where(id: b).index_by(&:id).slice(*b).values

与:

b = [5,3,3,1]
Country.where(id: b)
#=> [#<Country id: 1, name: "France">, #<Country id: 3, name: "Ukraine">, #<Country id: 5, name: "Spain">]
Country.where(id: b).index_by(&:id)
#=> {1=>#<Country id: 1, name: "France">, 3=>#<Country id: 3, name: "Ukraine">, 5=>#<Country id: 5, name: "Spain">}
Country.where(id: b).index_by(&:id).slice(*b)
#=> {5=>#<Country id: 5, name: "Spain">, 3=>#<Country id: 3, name: "Ukraine">, 1=>#<Country id: 1, name: "France">}
Country.where(id: b).index_by(&:id).slice(*b).values
#=> [#<Country id: 5, name: "Spain">, #<Country id: 3, name: "Ukraine">, #<Country id: 1, name: "France">]

当然,你也可以使用第一种方法b.uniq

关于ruby-on-rails - 根据数组对对象列表进行排序 (Rails),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41419169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com