[英]How do I chain multiple models to reduce the number of SQL queries
我正在尝试检查学生是否尝试过指定的测试。 我想链接相关模型以将查询数量减少到 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
我想检查特定学生(id:100)是否尝试过指定的测试,并检索其他详细信息,例如测试的主题名称。 到目前为止,我有这样的事情:
ta = Assign.includes(:test => {:topic => :attempts})
这允许我在单个查询中检索详细信息,例如 test_name、topic_name、分配时间等。 如何在同一个查询中包含 student_id: 100 的尝试记录? 以我现在所拥有的,当我检索学生的尝试详细信息时,正在生成一个全新的查询。
我想要的是类似于以下内容而无需再次触摸数据库:
ta.test.attempts.where(student_id: 100)
我如何只用一个查询来完成这一切?
好的,由于您想要所有连接表中的各种信息,因此您必须从一开始就将它们连接起来。
Attempt.joins(:topic, :test, :assign)
然后你可以用student_id
过滤它
.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")
总之
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.