gpt4 book ai didi

mysql - 预加载带条件的嵌套资源

转载 作者:行者123 更新时间:2023-11-29 11:00:36 30 4
gpt4 key购买 nike

在我的简单考勤应用程序中,有 :students:semesters:attendances。出勤率包含列 student:references season:references date:date present:boolean

学期.rb

class Semester < ApplicationRecord
has_and_belongs_to_many :students
accepts_nested_attributes_for :students
end

学生.rb

class Student < ApplicationRecord
has_and_belongs_to_many :semesters
has_many :attendances, dependent: :destroy
accepts_nested_attributes_for :attendances
end

出勤.rb

class Attendance < ApplicationRecord
belongs_to :semester
belongs_to :student
validates_presence_of :date
end

semesters#show 页面中,我想显示该学期的每个学生以及每个学生的出勤率,如下所示。

attendance

它有效,但在开始计数之前,我必须过滤掉一些与学期无关的:attendances。因此,我的目标是立即加载该学期、其学生以及仅属于该学期的出勤情况。

这样,当我使用时

@semester.students.each do |student|
student.attendances
end

.attendances 方法应该只返回与该学期相关的那些。这可能吗?

这是我得到的

# semesters_controller.rb
def show
@semester = Semester.includes(students: [:attendances])
.order('students.first_name')
.find params[:id]
end

# students_helper.rb
def student_attendance(student)
total = student.attendances.select { |x| x.semester_id == @semester.id }
present = total.select &:present
percent = (present.size/total.size.to_f * 100).round rescue 0
link_to student, class: 'attendance', style: "width: #{percent}%" do
<<-HTML.html_safe
<span>#{student.first_name}</span>
<span>#{percent}%</span>
HTML
end
end

我发现使用 select {|x| x.semester_id == @semester.id } 而不是 where season_id: @semester.idselect &:present 而不是 where present: true 减少查询数量。

无论如何,有没有一种方法可以加载 :attendances 这样我就不必经过第一个过滤器(select {|x| x.semester_id == @semester.id })?如果我没有像现在这样进行过滤,那么它将显示学生参加过的所有学期的出勤率,而不仅仅是我们试图在 #show 页面上显示的这一学期。

我只是不想加载所有不必要的数据,不是吗?谢谢。

最佳答案

看起来您已经有了一种将出勤率与学期直接联系起来的方法(如您的出勤类(class)中所述的 belongs_to :semester)。

你尝试过吗:

class Semester < ApplicationRecord
has_and_belongs_to_many :students
has_many :attendences
end
attendences = @semester.attendences

或者只是:

attendences = Attendence.where(semester: params[:id])

(您可以使用适当的联接/包含来减少 sql 查询)

关于mysql - 预加载带条件的嵌套资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42355335/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com