问题描述
|
我想得到尚未回答任何问题的ѭ0人。我该如何完成?
以下是我的模型及其相互之间的关系。
答案模型(字段:id,question_id,text):
class Answer < ActiveRecord::Base
belongs_to :inquiry
belongs_to :question
has_one :respondent,:through => :inquiry
validates_uniqueness_of :inquiry_id
validates_presence_of :text
end
受访者模型(字段:ID,电子邮件,user_id):
class Respondent < ActiveRecord::Base
has_many :inquiries,:dependent => :destroy
has_many :questions,:through => :inquiries
belongs_to :user
validates_uniqueness_of :email
validates_presence_of :email
end
查询模型(字段:id,question_id,responent_id):
class Inquiry < ActiveRecord::Base
belongs_to :question
belongs_to :respondent
has_one :answer,:dependent => :destroy
问题模型(字段:ID,文本):
class Question < ActiveRecord::Base
has_many :inquiries,:dependent => :destroy
has_many :answers,:through => :inquiries,:dependent => :destroy
belongs_to :user
end
解决方法
根据您需要此数据的上下文,并假设您没有太多的受访者和问题,您可以执行以下操作。假设您有一个名为Answer的方法?在问题模型中,如果回答了问题,则返回true。
respondents = []
Respondent.all.each do |respondent|
total_questions = respondent.questions.count
answered_questions = 0
unless total_questions < 1
respondent.questions.each do |q|
q.answered? ? answered_questions++ : nil
end
end
if answered_questions == 0
respondents << respondent
end
end
最后,您剩下了一系列响应对象,这意味着您可以对其进行迭代以获取ID。