Calculations based on multiple tables


#1

Hi there,

I’m trying to grab all the contest_entries from a particular contest,
and
then grab all the appropriate contest_ratings associated with the songs
and
contest. The end result is an average score for each song involved in
each
contest.

I made an ERD of my table structure which can be found at:

Here’s my model structure:

class Contest < ActiveRecord::Base
has_many :contest_entries
has_many :songs, :through => :contest_entries
end

class ContestEntry < ActiveRecord::Base
belongs_to :song
belongs_to :contest
has_many :contest_ratings
end

class ContestRating < ActiveRecord::Base
belongs_to :contest_entry
end

class Song < ActiveRecord::Base
belongs_to :member
has_many :contest_entries, :dependent => true
end

class Member < ActiveRecord::Base
has_many :songs, :order => :position
end

This is what I’m currently doing to perform the average on each song,
but it
seems like there should be a better way.

def show_contest
@contest = Contest.find(params[:id])
@contest_entries = ContestEntry.find_all_by_contest_id(@contest.id)
@contest_entries.each do |contest_entry|
songs = ContestRating.find_all_by_contest_entry_id
(contest_entry.id.to_s)
total = 0
songs.each do |song|
total += song.score
end
average_score = total.to_f / songs.size.to_f
song_name = Song.find_by_id(contest_entry.song_id)
end
end

Thank you,
Dave H.