我尝试根据关联值添加范围。
我有两个班级:
class Question < ActiveRecord::Base
has_many :quiz_questions
scope :entro, -> { where 'quiz_type = ?', 'base' }
scope :oltre, -> { where 'quiz_type = ?', 'oltre' }
end
class QuizQuestion < ActiveRecord::Base
belongs_to :question
scope :errors, -> { where 'correct = ?', false }
scope :no_errors, -> { where 'correct = ?', true }
end
我用
self.quiz_questions.merge(Question.entro)
我有这个错误。
PG::UndefinedColumn: ERROR: column "quiz_type" does not exist
LINE 1: ...ions" WHERE "quiz_questions"."quiz_id" = $1 AND (quiz_type ...
^
: SELECT "quiz_questions".* FROM "quiz_questions" WHERE "quiz_questions"."quiz_id" = $1 AND (quiz_type = 'base')
我只需要从一系列测验问题中计算我的收藏中有多少问题{ where 'quiz_type = ?', 'base' }
。
更新
QuizQuestion是Quiz类和Question Class之间的连接表。我简化了课程。
顺便说一句,quiz_questions集合是这样的:
#<QuizQuestion id: 12436, quiz_id: 315, question_id: 253, created_at: "2014-11-07 13:06:18", updated_at: "2014-11-07 13:11:10", solution: 1575, correct: true>,
#<QuizQuestion id: 12437, quiz_id: 315, question_id: 538, created_at: "2014-11-07 13:06:18", updated_at: "2014-11-07 13:11:10", solution: 2429, correct: true>,
#<QuizQuestion id: 12441, quiz_id: 315, question_id: 395, created_at: "2014-11-07 13:06:18", updated_at: "2014-11-07 13:11:10", solution: 1999, correct: true>,
我在联接表中使用一个字段来标记用户是否已回答问题的权利。
quiz_questions.errors.count
给我总错误。我现在需要按类型对总错误进行分组,并且quiz_type字段位于相关的问题模型中。
答案 0 :(得分:2)
尝试更新范围以使用散列样式,这样可确保将列转换为"questions"."quiz_type"
而不是使用quiz_type
。它可能会修复它,你可能必须加入而不是合并,如果它不能解决它
scope :entro, -> { where quiz_type: 'base' }
scope :oltre, -> { where quiz_type: 'oltre' }
答案 1 :(得分:0)
我找到了解决方案
quiz_questions.joins(:question).merge(Question.entro)