0

class QuestionGroup < ActiveRecord::Base
  has_many :questions
end

class Question < ActiveRecord::Base
  belongs_to :question_group
  has_many :question_answers
  has_many :question_users_answers, :through => :question_answers, :source => :user_question_answers

  def self.questions_without_answers(user_id)
    select {|q| q.question_users_answers.where(:user_id=>user_id).empty?}
  end
end

class QuestionAnswer < ActiveRecord::Base
  belongs_to :question
  has_many :user_question_answers
end

如果没有用户答案,我需要找到所有问题我通过类方法self.questions_without_answers(user_id)

但是我怎样才能找到所有存在 questions_without_answers 和特定用户的 QuestionGroups?

PS:我需要找到所有未回答的问题以及拥有这些问题的所有组,我可以通过findnamed-scope来完成吗?

更新:

  def self.groups_without_answers(user_id)
    questions_ids = Question.questions_without_answers(user_id).map {|q| q.id}
    all(:conditions => "id in (select distinct question_group_id from questions where id in (#{questions_ids.join(',')}))")
  end

但我认为这不好,或者我错了?

4

1 回答 1

0
class QuestionGroup < ActiveRecord::Base
  has_many :questions

  def self.without_answers(user_id)
    joins(%"inner join questions on question_groups.id = questions.question_group_id
            inner join question_answers
              on question_answers.question_id = questions.id
            inner join question_groups
              on question_answers.question_users_answers_id = question_users_answers.id").where("user_question_answers.user_id" => user_id).select { |qq| ... }
    end
  end
end

您可以将一些内部联接更改为 leftout join 以获取您要加入的表不匹配的记录,例如没有 answer的记录。您要加入的表的字段的所有字段都将具有 NULL 值。添加 where id is null甚至会过滤到没有答案的问题。

请记住,这只是一种替代技术。您可以通过以下方式以编程方式简单地解决问题:

class QuestionGroup
  def self.question_groups_without_answers(user_id)
    select {|qq| qq.question_users_answers.where(:user_id=>user_id).empty?}.map{ |qq| qq.question_group }
  end
end

进行联接的一个优点是数据库会完成所有工作,并且您不需要向数据库发送多个 SQL 查询,因此速度会快得多

于 2012-09-27T15:54:46.523 回答