0

タイトルは簡単に言えば問題です。私が使用している単純化されたモデルは次のとおりです。

class Test
  include Mongoid::Document

  field :name, :type => String
  embeds_many :questions
  attr_accessible :name, :questions      
end

class Question
  include Mongoid::Document

  field :text, :type => String

  embedded_in :test
  has_many :answers
  attr_accessible :text, :test, answers    
end

class Answer
  include Mongoid::Document

  field :value, :type => Integer

  belongs_to :question
  belongs_to :user
  attr_accessible :value, :question, :user      
end

class User
  include Mongoid::Document

  has_many :answers
  attr_accessible :answers    
end 

最小限のデータベース クエリで、ユーザーのテストで未回答の質問をすべて取得できるようにしたいと考えています。

これは私がこれまでに考えた最善の解決策です

answered = []
user.answers.each {|a| answered << a.question_id}
test.questions.where(:_id.nin => answered).length

これに関するヘルプは大歓迎です。

4

1 に答える 1

1

UPDATE : 制約付き選択が存在しないことを照会する必要があります。

test.questions.find_by_sql("WHERE NOT EXISTS (SELECT id FROM answers WHERE answers.question_id = questions.id AND answers.user_id = #{user.id}") 

または条件付き結合のカウント 0

test.questions.joins("INNER JOIN answers ON answers.question_id = questions.id AND answers.user_id = #{user.id} AS user_answers").where('COUNT(user_answers.id) = 0')

これらが機能するかどうか教えてください。彼らのパフォーマンスに関する洞察はありますか?

元の回答、間違っているため、ユーザーからのまったく回答されていない質問が必要であると想定していました。

回答にカウンター キャッシュを使用します。これは、質問のデータベース テーブルに answer_count 整数列があることを前提としています。

class Answer
  include Mongoid::Document

  field :value, :type => Integer

  belongs_to :question, :counter_cache => true
  belongs_to :user
  attr_accessible :value, :question, :user      
end

これを考えると、クエリは次のようになります。

test.questions.where(answers_count: 0, user_id: user)
于 2012-06-03T13:03:37.433 に答える