如何从2个表中获取数据?

时间:2011-05-30 07:36:37

标签: ruby-on-rails

我希望得到id未回答任何问题的受访者。我该如何做到这一点?

以下是我的模型及其相互之间的关系。

答案模型(字段:id,inquiry_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,email,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,respondent_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

1 个答案:

答案 0 :(得分:0)

根据您想要此数据的上下文,并假设您没有太多的受访者和问题,您可以执行以下操作。假设你有一个叫做回答的方法?在你的问题模型中,如果问题得到解答,则返回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。