簡體   English   中英

ActiveRecord關聯值范圍

[英]Activerecord scope on association value

我試圖添加基於關聯值的范圍。

我有兩節課:

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類之間的聯接表。 我簡化了課程。

順便說一句,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字段位於關聯的問題模型中。

嘗試更新范圍以使用哈希樣式,這將確保將列轉換為"questions"."quiz_type"而不是使用quiz_type 它可能會解決它,如果不能解決問題,您可能必須加入聯接而不是合並

scope :entro,     -> { where quiz_type: 'base' }
scope :oltre,     -> { where quiz_type: 'oltre' }

我找到了解決方案

quiz_questions.joins(:question).merge(Question.entro)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM