我有一个查询*,结果如下:
#<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
对于查询,我已经使用了两个具有相关 ID 的数组Book
和ListEdition
:
BookRank.where(:book_id => book_ids, :list_edition_id => list_edition_ids)