Brains for Business, Inc.

Brains for Business, Inc.

Software Development & Consulting

  • Home
  • The Institute on Women
  • About

Using named_scope to filter records

Posted in Ruby on Rails by dave.parfrey
May 13 2010
TrackBack Address.

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:

  • named_scope
  • has_finder (which became named_scope)
Leave a Comment
Click here to cancel reply.

Site Search

Categories

  • Software Development  (8)
    • iPhone/iPod/iPad  (4)
    • Reading Material  (1)
    • Ruby on Rails  (3)

RSSLatest Tweets

  • Twitter is unavailable
Copyright ©2009 by Brains for Business, Inc. All Rights Reserved.