0

I have the following tables:

class FinalExam < ActiveRecord::Base
  belongs_to :course
  has_many :pages, :as => :course_unit, :dependent => :destroy
end

class Page < ActiveRecord::Base
  belongs_to :course_unit, :polymorphic => true
  has_one :quiz
  has_one :slide
end

class Quiz < ActiveRecord::Base
  belongs_to :page
end

class Answers < ActiveRecord::Base
  belongs_to :quiz
end

So, we have Answer.Quiz.Page.FinalExam

Given the FianlExam id, what is the fastest way to find all Answers count ? how to get it ?

I can re-design the DB to have belongs_to :final_exam in Answers

class Answers < ActiveRecord::Base
  belongs_to :quiz
  belongs_to :final_exam
end

this way, I can say Answers.where(:final_exam_id=> params[:id]).count

Do I have to change the DB design ? or its a matter of a query ?

I need an expert advice please.

Alex Peattie
  • 26,633
  • 5
  • 50
  • 52
simo
  • 23,342
  • 38
  • 121
  • 218

1 Answers1

1

First of all I'm guessing that Quiz should read:

class Quiz < ActiveRecord::Base
  belongs_to :page
  has_many :answers
end

If so you can add these lines to your FinalExam model:

has_many :quizzes, :through => :pages
has_many :answers, :through => :quizzes

Allowing you to then call

FinalExam.first.answer.count

(Note: if you're on a version of Rails < 3.1, you'll need this plugin)

The drawback to this approach is that it becomes slow with a lot of data. In this case, you'd want to set up a counter cache in the FinalExam that updates every time an answer is added. It'd a little more complicated because of the many-layered relationships you have; see this post for more info:

counter_cache has_many_through sql optimisation, reduce number of sql queries

Community
  • 1
  • 1
Alex Peattie
  • 26,633
  • 5
  • 50
  • 52
  • what about adding "belongs_to :final_exam" to Answer ? and then using: Answers.where(:final_exam_id=> params[:id]).count, do you recommend it to stay away from complexities ? – simo Nov 12 '11 at 06:54
  • You'd also have to add FinalExam has_many :answers. I'd recommend against this, because then you have ambiguous relationships: A final exam's answers who'd be separate from a final exam's quizzes answers. You'd have to keep the two sets of answers in sync and it would be a bit of a nightmare. has_many :through is the preferred way to do what you're trying to do. – Alex Peattie Nov 12 '11 at 17:25