The title is the problem in a nutshell. Here are the simplified models I am using :
class Test
include Mongoid::Document
field :name, :type => String
embeds_many :questions
attr_accessible :name, :questions
end
class Question
include Mongoid::Document
field :text, :type => String
embedded_in :test
has_many :answers
attr_accessible :text, :test, answers
end
class Answer
include Mongoid::Document
field :value, :type => Integer
belongs_to :question
belongs_to :user
attr_accessible :value, :question, :user
end
class User
include Mongoid::Document
has_many :answers
attr_accessible :answers
end
I want to be able to retrieve all the unanswered questions in a test for a user with the minimal amount of database queries.
This is the best solution I have thought up so far
answered = []
user.answers.each {|a| answered << a.question_id}
test.questions.where(:_id.nin => answered).length
Any help with this is much appreciated.
UPDATE:
you need to query for the non-existence of a constrained select:
or count 0 of a conditional join
let me know if these work. any insight on their performance?
ORIGINAL ANSWER, INCORRECT cos it was assuming we need totally unanswered questions ASKED by the user:
use a counter cache on answers. This assumes an answers_count integer column on the questions db table.
Given this, your query can be: