How to get data from 2 tables?
I want to get the id
s of respondents who have not answered any questions. How do I accomplish this?
Below are my models and their relationships to each other.
Answer model (fields: id, inquiry_id, text):
开发者_StackOverflow中文版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
Respondent model (fields: 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
Inquiry model (fields: id, question_id, respondent_id):
class Inquiry < ActiveRecord::Base
belongs_to :question
belongs_to :respondent
has_one :answer, :dependent => :destroy
Question model (fields: id, text):
class Question < ActiveRecord::Base
has_many :inquiries, :dependent => :destroy
has_many :answers, :through => :inquiries, :dependent => :destroy
belongs_to :user
end
Depending on the context in which you want this data, and assuming you dont have too many Respondents and Questions you could do the following. This assumes you have a method called answered? in your question model that returns true if the question is answered.
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
At the end you are left with a array of respondent objects, meaning you can iterate over it to get the ids.
精彩评论