Rails has_many 联合查询

udasker_pictureudasker 213天前发布 0 浏览 1 关注

现有3个model表,对应关系分别是:

class Exercise < ApplicationRecord
  has_many :exercise_questions
end
class ExerciseQuestion < ActiveRecord::Base
   belongs_to :exercise
  has_many :exercise_standard_answers, :dependent => :destroy
end
class ExerciseStandardAnswer < ActiveRecord::Base
  belongs_to :exercise_question, optional:true
end

那么现在我需要的是要获得一个 exercise的全部 exercise_questions中某一类型的问题,且它们的 exercise_standard_answers的数量大于1.

该怎么做呢?

udasker_picture
做有意义的事
213天前发布
@exercise.exercise_questions.where("question_type = ?",1).joins(:exercise_standard_answers).group(:id).having('COUNT(exercise_standard_answers.exercise_question_id) > 1')

学习了哈 udasker 211天前发布