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

标签 mysql ruby-on-rails ruby

在我的简单考勤应用程序中,有 :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/

相关文章:

ruby-on-rails - 在 Rails 中的不同模型查询中搜索

ruby-on-rails - Windows 上的 Ruby/Rails 前纪元日期

php - MySQL可以从多级父子关系中计算总计吗?

mysql - 仅从 MySQL Workbench 图/模型更新?

MySQL:更改当前用关键字命名的列名

ruby-on-rails - Rails 3.2 ajax 示例, Controller 中带有参数

ruby-on-rails - 在 Rails4.1 中放置 Rack 中间件的位置

php - Laravel 是如何管理 MySQL 变量的?

jquery - 世界上最愚蠢的人(我)的 Rails 教程?

sql - Rails 应用程序外键错误 : Administrative user not allowed to delete other users in