【发布时间】:2014-05-03 18:07:44
【问题描述】:
我有以下型号:
class Student
attr_accessible :name
has_many :courses, through: :course_students
has_many :course_students
end
class Course
attr_accessible :name
has_many :students, through: :course_students
has_many :course_students
end
class CourseStudent
attr_accessible :grade
belongs_to :course
belongs_to :student
end
现在,我正在尝试生成一个 Excel 表格,其中学生为行,课程为列,交叉点将显示学生在该课程中的成绩。
到目前为止,我处理的是一小群学生,所以下面的算法是可以的:
<table>
...
<tbody>
<% @students..includes(:courses)each do |student| %>
<tr>
...
<% student.courses.includes(:course_students).each do |course| %>
<td><%= course.course_students.find_by_student_id(student.id).try(:grade) || '-' %></td>
<% end %>
</tr>
<% end %>
</tbody>
</table>
如您所见,我一直在尝试在加载数据时包含课程和 course_students,但仍然收到大量查询。我知道这是一个经典的 N+1 查询问题(更像是 NxM+N+M+1),但通常的方法不起作用。
我希望在更少的查询中提取我需要的所有数据。有人有想法吗?
【问题讨论】:
标签: sql ruby-on-rails has-many-through