I'm trying to limit a has_many through association for certain instances where I want to limit the number of results when using .includes(:model)
Here's what I have so far:
class Student < ActiveRecord::Base
has_many :courses, :through => :students_courses
has_many :sample_courses, :through => :students_courses, :limit => 3, :source => :course, :order => 'updated_at DESC'
end
class Course < ActiveRecord::Base
has_many :students, :through => :students_courses
end
So far so good. If I fire up the rails console and load up students, I can access the sample course and three results are returned. However, when I have a query and try includes
, then in the view trying to print out the course names it loads all the courses for the student, not just three.
# Query in controller
@students.where(...stuff..).includes(:sample_courses)
# In the view -
@students.each do |student| courses = student.sample_courses
That last courses
variable returns all of the courses associated with the student, not just the three sample courses. If I skip the includes
in the controller and keep the view identical then it correctly queries for the sample courses. Of course you're then running n-number of queries which I'm trying to avoid.
So how can I eager load 3 courses?
The :limit
has ignore when you use eager load an association, as in API document say:
If you eager load an association with a specified :limit option, it will be ignored, returning all the associated objects, example:
class Picture < ActiveRecord::Base
has_many :most_recent_comments, :class_name => 'Comment', :order => 'id DESC', :limit => 10
end
Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments.
If you want to load 3 courses, maybe you can use this:
courses = student.sample_courses.limit(3)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.