我在Rails应用程序中有这些模型:
class Course < ActiveRecord::Base
has_many :topics
end
class Topic < ActiveRecord::Base
has_many :parts
belongs_to :course
end
class Part < ActiveRecord::Base
has_many :quizzes
belongs_to :topic
end
class Quiz < ActiveRecord::Base
has_many :quiz_submissions
belongs_to :part
end
class QuizSubmission < ActiveRecord::Base
belongs_to :quiz
end
现在我想获得所有QuizSubmissions的课程ID,即每个quiz_submission的quiz_submission.quiz.part.topic.course.id
。
我当前的代码是QuizSubmission.all.map{|qs| qs.quiz.part.topic.cours.id}
,这个代码非常慢,我也尝试了joins
,仍然没有提高性能。也许我错误地使用了joins
。
有什么建议吗?我应该QuizSubmission belongs_to :course
吗?谢谢!
答案 0 :(得分:1)
你可以这样做:
QuizSubmission.joins(:quiz => {:part => {:topic => :course}}).
select('quiz_submissions.id, courses.id as course_id')
答案 1 :(得分:0)
你可以尝试
Course.joins({ topics: { parts: { quizzes: :quiz_submissions } } }).map(&:id)
答案 2 :(得分:0)
如果我理解了问题,那就是如何在没有加入的情况下快速获得ID。
quiz_subm_ids = QuizSubmission.pluck(:id)
part_ids = Part.where(quiz_submission_id: quiz_subm_ids).pluck(:id)
topic_ids = Topic.where(part_id: part_ids).pluck(:id)
course_ids = Topic.where(topic_id: topic_ids).pluck(:id)