Forum: Ruby on Rails Calculations based on multiple tables

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
12be02204a4bcaeec2c6c369fe53a45b?d=identicon&s=25 Dave Hoefler (Guest)
on 2006-06-09 21:49
(Received via mailing list)
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:
http://antrover.com/erd/contest_question.jpg

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 Hoefler
This topic is locked and can not be replied to.