Patricio S
Patricio S

Reputation: 2130

Why am I getting only the last associated record with includes?

For the sake of simplicity, I have a Course and a Student model, Courses has many Students and Students belongs to a Course (I know it's kinda a stupid example cause a Student can only be associated with 1 Course, but whatever)

I made a scope in the Course model to get the Courses which have more than 'x' number of students:

scope :with_more_students_than, -> (students_number) { joins(:students).having("count(course_id) > #{students_number}").group('course_id') }

Then in the controller I get the Courses with more than 5 Students:

@courses_with_more_than_x_students = Course.with_more_students_than(5).includes(:students)

And then I show them:

<% @courses_with_more_than_x_students.each_with_index do |course, i| %>
    <h2><%= "#{i + 1} #{course}" %></h2>
    <% course.students.each_with_index do |student, j| %>
        <p><%= "#{j + 1} #{student}" %></p>
    <% end %>
<% end %>

With the .includes(:students) it only shows the last Student, without it I see every Student of those Courses, why?

Upvotes: 0

Views: 43

Answers (1)

Pavel Mikhailyuk
Pavel Mikhailyuk

Reputation: 2877

Try

@courses_with_more_than_x_students = Course.with_more_students_than(5).preload(:students)

We probably have different DB, so it works for me with slightly different scope:

scope :with_more_students_than, -> (students_number) {
  joins(:students).having("count(courses.id) > #{students_number}").group('courses.id')
}

OR with students.course_id column.

Upvotes: 0

Related Questions