Rails / ActiveRecord查询尚未回答的测验问题

时间:2014-11-21 19:57:29

标签: ruby-on-rails ruby rails-activerecord

我收到的所有问题都是学生尚未正确回答。

correct_questions = QuizQuestionResponse.where(correct: true, user_id: current_user.id, lesson_id: params[:quiz_response][:lesson_id])
questions = QuizQuestion.where('lesson_id = ? AND id not in (?)', params[:quiz_response][:lesson_id], correct_questions)

有没有办法以更优雅和有效的方式写出来?

1 个答案:

答案 0 :(得分:0)

我假设原始查询不正确,因为您使用QuizQuestionResponse ID作为QuizQuestion id的参数。

correct_question_ids = QuizQuestionResponse.where(correct: true, user_id: current_user.id, lesson_id: params[:quiz_response][:lesson_id]).pluck(:question_id)
questions = QuizQuestion.where(lesson_id: params[:quiz_response][:lesson_id]).where.not(id: correct_question_ids)

not方法适用于Rails 4 +