繁体   English   中英

rails 3 eager load has_many通过与limit的关联

[英]rails 3 eager load has_many through association with limit

我正在尝试通过关联来限制has_many,以便在使用.includes(:model)时我想限制结果数量的某些实例

这是我到目前为止所拥有的:

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

到现在为止还挺好。 如果我启动rails控制台并加载学生,我可以访问示例课程并返回三个结果。 但是,当我有一个查询并尝试includes ,然后在视图中尝试打印出课程名称,它会加载学生的所有课程,而不仅仅是三个。

# Query in controller
@students.where(...stuff..).includes(:sample_courses)

# In the view -
@students.each do |student| courses = student.sample_courses

最后一个courses变量返回与学生相关的所有课程,而不仅仅是三个示例课程。 如果我跳过控制器中的includes并保持视图相同,则它会正确查询示例课程。 当然,你正在运行我试图避免的n个查询。

那么我怎样才能加载3门课程呢?

当你使用eager加载关联时, :limit会被忽略,如在API文档中所说:

如果您急切地使用指定的:limit选项加载关联,它将被忽略,返回所有关联的对象,例如:

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.

如果你想加载3门课程,也许你可以使用这个:

courses = student.sample_courses.limit(3)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM