views:

304

answers:

1

I am building an app for cognitive tests in Rails.
I have a number of tests (Quiz objects) for my visitors. In the home page I want to show only quizzes that are ready for consumption: they must have a number of questions and a number of possible answers.
Of course I could query with SQL, or create a class method retrying all objects where Quiz.questions.size > 1 && Quiz.answer.size > 1. Still, I'd like a more elegant/abstracted way.
Is there a way to query have a 'ready' method acting as if it were an ActiveRecord method, so I can call Quiz.find_all_by_ready(1) and put ready in any quiz condition? Caching is a possibility, I was wondering if there was a dynamic alternative. How would a rails guru solve the problem?

Cheers,
Davide

+2  A: 

Using a combination of named_scope and counter_caches you could do something like this:

class Quiz < AR:B
    named_scope :ready, :conditions => ['quizes.questions_count > 0 AND quizes.answers_count > 0']
end

@quizes = Quiz.ready

I hope this helps!

jonnii
I guess that's the most straightforward solution, thanks!
nutsmuggler