简而言之,标题就是问题。以下是我正在使用的简化模型:
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
我希望能够以最少的数据库查询为用户检索测试中所有未回答的问题。
这是迄今为止我想到的最好的解决方案
answered = []
user.answers.each {|a| answered << a.question_id}
test.questions.where(:_id.nin => answered).length
对此的任何帮助都非常感谢。