Rails:如何获取深度为2’has_many’级别的记录?

我已经设置了这些模型:

Course has_and_belongs_to_many Student Student has_and_belongs_to_many Course has_many Books Book belongs_to Student 

如何使用ActiveRecord高效获取课程的所有书籍?

试试这个:

 Course.includes(:students => { :books }) 

文档在这里 ,在“渴望加载关联”下。

编辑

对不起,我误解了这个问题。 我看到你关注的是特定课程的书籍。 在这种情况下,我会建议这样的事情:

 Book.includes(:student => :courses).where(["course.id = ?", @course.id]).limit(5) 

Course模型中添加此方法可能更容易:

 class Course < ActiveRecord::Base def books(max = 10) Book.includes(:student => :courses).where(["course.id = ?", self]).limit(max) end end 

该代码可能不完全正确,但它应该给你正确的想法。

此外,您可能希望查看此问题,以寻找自己定义此内容的潜在替代解决方案。

我想知道你是否可以使用通过关联并做类似的事情……

 Course has_and_belongs_to_many :students has_many :books, :through => :students Student has_and_belongs_to_many :courses has_many :books Book belongs_to :student 

现在您可以调用Course.books,它将返回与课程相关的所有书籍。