gpt4 book ai didi

ruby-on-rails - rails/ ruby : turning query result into multi-level hash

转载 作者:数据小太阳 更新时间:2023-10-29 08:42:48 24 4
gpt4 key购买 nike

我有一个查询*,结果如下:

#<ActiveRecord::Relation [
#<BookRank id: 2, book_id: 2, list_edition_id: 1, rank_world: 5, rank_europe: 1>,
#<BookRank id: 3, book_id: 1, list_edition_id: 1, rank_world: 6, rank_europe: 2>,
#<BookRank id: 8, book_id: 2, list_edition_id: 3, rank_world: 1, rank_europe: 1>,
#<BookRank id: 9, book_id: 1, list_edition_id: 3, rank_world: 2, rank_europe: 2
]>

我想要得到的是这样的哈希:

{
book_id => {
list_edition_id => {
"rank_world" => value,
"rank_europe" => value
}
}
}

(最重要的是根据最低 list_edition_id 的 rank_world 值对哈希进行排序,但这可能太复杂了。)

ranks_relation.group_by(&:book_id) 给我一个散列,其中 book_ids 是键,但排名数据仍在数组中:

{
2 => [
#<BookRank id: 2, book_id: 2, list_edition_id: 1, rank_world: 5, rank_europe: 1>,
#<BookRank id: 8, book_id: 2, list_edition_id: 3, rank_world: 1, rank_europe: 1>
],
1 => [
#<BookRank id: 3, book_id: 1, list_edition_id: 1, rank_world: 6, rank_europe: 2>
#<BookRank id: 9, book_id: 1, list_edition_id: 3, rank_world: 2, rank_europe: 2>
]
}

我应该如何进行?

*编辑: 这是模型结构和查询。另一位用户要求:

class Book < ActiveRecord::Base
has_many :book_ranks, dependent: :destroy
end

class List < ActiveRecord::Base
has_many :list_editions, dependent: :destroy
end

class ListEdition < ActiveRecord::Base
belongs_to :list
has_many :book_ranks, dependent: :destroy
end

class BookRank < ActiveRecord::Base
belongs_to :book
belongs_to :list_edition

has_one :list, through: :list_edition
end

对于查询,我已经使用了两个数组,其中包含 BookListEdition 的相关 ID:

BookRank.where(:book_id => book_ids, :list_edition_id => list_edition_ids)

最佳答案

试试这个

record = your_record

hash = {}

record.each do |record|
hash[record.book_id] ||= {}
hash[record.book_id][record.list_edition_id] = {
'rank_world' => record.rank_world,
'rank_europe' => record.rank_europe
}
end
# hash will then be {2=>{1=>{"rank_world"=>5, "rank_europe"=>1}, 3=>{"rank_world"=>1, "rank_europe"=>1}}, 1=>{1=>{"rank_world"=>6, "rank_europe"=>2}, 3=>{"rank_world"=>2, "rank_europe"=>2}}}

这将仅遍历记录一次。

关于ruby-on-rails - rails/ ruby : turning query result into multi-level hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51171568/

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