Here’s a simple RoR solution to an interesting database problem. Assume you have a web-based quiz. There’s a ”questions” table with the questions, a “tests” table with the total results, and an “answers” table with answers to individual questions. Here’s the Model classes:
class Question < ActiveRecord::Base has_many :answers end class Tests < ActiveRecord::Base has_many :answers end class Answer < ActiveRecord::Base belongs_to :question belongs_to :test end
The problem is, you don’t typically want to see all the answers to a question, just the ones for the test you’re displaying. The solution is to use named_scope, as follows:
class Question < ActiveRecord::Base has_many :answers # returns the answer for the given test def answer_for_test test answers.for_question_and_test(self, test).first end end class Tests < ActiveRecord::Base has_many :answers end class Answer < ActiveRecord::Base belongs_to :question belongs_to :test named_scope :for_question_and_test, lambda { |question, test| { :conditions => ['question_id = ? and test_id = ?', question.id, test.id] } } end
Pretty simple! For more information about this solution, here’s the articles I used to research the issue: