I have a query* that results in the following:
#<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
]>
What I am trying to get is a hash like this:
{
book_id => {
list_edition_id => {
"rank_world" => value,
"rank_europe" => value
}
}
}
(The cherry on top would be to order the hash by the rank_world value for the lowest list_edition_id, but that may be too complex perhaps.)
ranks_relation.group_by(&:book_id)
gives me a hash where the book_ids
are keys, but then the ranks data is still in arrays:
{
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>
]
}
How should I proceed?
*EDIT: This is the model structure and query. Another user asked for it:
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
For the query, I already use two arrays with the relevant IDs for Book
and ListEdition
:
BookRank.where(:book_id => book_ids, :list_edition_id => list_edition_ids)