xhocquet
xhocquet

Reputation: 380

How to group by individual elements in arrays

I have collections of shows with their genres attached, so that Show.first.genres returns ['horror','scifi',etc].

My goal is to calculate a users mean score by unique genres. The problem is that if I do a Show.group(:genres), I get results by the whole sets of genres:

['horror','scifi']=>[list of entries]
['horror','gore']=>[list of entries]

I would rather get a count of all elements with horror in the genres, all elements with scifi, etc. Any ideas?

Here's some relevant schema information:

create_table "animes", force: :cascade do |t|
end

create_table "animes_genres", id: false, force: :cascade do |t|
 t.integer "anime_id", null: false
 t.integer "genre_id", null: false
end

create_table "genres", force: :cascade do |t|
 t.string "name"
end

create_table "library_entries", force: :cascade do |t|
end

These are all linked back and forth and I can generally access any relationships that exist via ActiveRecord.

Upvotes: 2

Views: 79

Answers (3)

Helder Pereira
Helder Pereira

Reputation: 5756

Or in a more Railsish way, you should probably start from Genre and do something like:

Genre.all.map{|g| [g, g.shows] }.to_h

Upvotes: 1

Helder Pereira
Helder Pereira

Reputation: 5756

I am not sure if this is what you are looking for, but if that Show.group(:genres) returns a Hash of [array of genres] => [array of entries], you can transform that into a Hash of genre => [array of entries], by doing this:

by_genres = Show.group(:genres)
by_genre = {}
by_genre.default = []
by_genres.each{|ks,vs| ks.each{|k| by_genre[k] += vs }}

Or if you only want the count:

by_genres = Show.group(:genres)
count_genre = {}
count_genre.default = 0
by_genres.each{|ks,vs| ks.each{|k| count_genre[k] += vs.size }}

Upvotes: 0

Jwashton
Jwashton

Reputation: 302

If the ActiveRecord Association goes both directions, then you should be able to look at the problem from the Genre Model's perspective.

Genre.find('space opera').shows

Upvotes: 0

Related Questions