2011-05-30 80 views
1

我想獲得沒有回答任何問題的受訪者的id。我該如何做到這一點?如何從2個表格中獲取數據?

以下是我的模型及其相互之間的關係。

答模型(字段:ID,inquiry_id,文本):

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 ,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 

回答

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。

+0

謝謝,但很抱歉,即時通訊欄中的新手,導致軌道錯誤'q.answered? ? answers_questions ++:無'...有什麼問題?而我應該寫什麼呢? – 2011-05-30 09:24:24

+0

我寫的代碼是示例代碼,所以它假定有回答?方法在你的問題模型中檢查問題是否已被回答,如果回答爲真,否則返回false。 – 2011-05-30 09:26:06