如何链接多个模型以减少SQL查询的数量

如何链接多个模型以减少SQL查询的数量,sql,ruby-on-rails,activerecord,Sql,Ruby On Rails,Activerecord,我试图检查学生是否尝试了指定的测试。我想链接相关模型,将查询数量减少到1个。以下是我的模型: class Test < ActiveRecord::Base has_many :assigns has_many :attempts belongs_to :topic end class Topic < ActiveRecord::Base has_many :tests has_many :attempts has_many :as

我试图检查学生是否尝试了指定的测试。我想链接相关模型,将查询数量减少到1个。以下是我的模型:

class Test < ActiveRecord::Base
  has_many   :assigns
  has_many   :attempts
  belongs_to :topic
end

class Topic < ActiveRecord::Base
  has_many    :tests
  has_many    :attempts
  has_many    :assigns, through: :test
end

class Assign < ActiveRecord::Base
  belongs_to  :test
  belongs_to  :student
  has_many    :attempts
end

class Attempt < ActiveRecord::Base
  belongs_to  :test
  belongs_to  :topic
  belongs_to  :assign
  belongs_to  :student
end
这允许我在单个查询中检索详细信息,如测试名称、主题名称、分配时间等。如何在同一查询中也包含student_id:100的尝试记录?根据我现在所拥有的,当我检索学生的尝试详细信息时,将生成一个全新的查询

我想要的是如下内容,而不必再次触碰数据库:

ta.test.attempts.where(student_id: 100)

如何仅通过一个查询就完成所有这些工作?

好的,因为您需要所有联接表中的各种信息,所以必须从一开始就联接它们

尝试.连接(:主题,:测试,:分配)

然后您可以使用
学生id

.where(“尝试.学生id”=>100)

最后,是您想要的字段

。选择(“尝试.id作为尝试\u id,测试.name作为测试\u名称,主题.name作为主题\u名称,分配.created\u at作为分配的\u at”)

总之

Attempt
    .joins(:topic, :test, :assign)
    .where("attempts.student_id" => 100)
    .select("attempts.id as attempt_id, tests.name as test_name, topics.name as topic_name, assigns.created_at as assigned_at")

分配
主题
尝试
是否需要
测试
前缀?这里发生的事情太多了,读起来有点难。你能做一个ER图吗?@Lusketteer为了清晰起见删除了测试。
Attempt
    .joins(:topic, :test, :assign)
    .where("attempts.student_id" => 100)
    .select("attempts.id as attempt_id, tests.name as test_name, topics.name as topic_name, assigns.created_at as assigned_at")