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

ユーザーの回答がない場合は、すべての質問を検索する必要があります

しかし、特定のユーザーに対して、questions_without_answers が存在するすべての QuestionGroups を見つけるにはどうすればよいでしょうか?

PS: 未回答のすべての質問と、これらの質問を所有するすべてのグループを検索する必要があります。 findまたはnamed-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

内部結合の一部を除外結合に変更して、結合しているテーブルが一致しないレコード(たとえば、回答がない場合)を取得できます。結合しているテーブルのフィールドは、すべてのフィールドでNULL値になります。where idが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 に答える