扶手:如何获取这是2'的has_many'级深的记录? [英] Rails: How to fetch records that are 2 'has_many' levels deep?
问题描述
我有这些模型建立:
Course
has_and_belongs_to_many Student
Student
has_and_belongs_to_many Course
has_many Books
Book
belongs_to Student
我如何有效地得到所有的书籍为一个疗程用ActiveRecord?
How do I efficiently get all the Books for a Course with ActiveRecord?
推荐答案
试试这个:
Course.includes(:students => { :books })
文件是这里,根据预先加载关联。
Documentation is here, under "Eager loading of associations".
编辑
对不起,我误解了问题。我看到你的重点是书本上的一个给定的课程。在这种情况下,我建议是这样的:
Sorry, I misread the question. I see your focus is on the books for a given course. In that case I would recommend something like this:
Book.includes(:student => :courses).where(["course.id = ?", @course.id]).limit(5)
这可能会更容易添加此作为对课程
模式的方法:
class Course < ActiveRecord::Base
def books(max = 10)
Book.includes(:student => :courses).where(["course.id = ?", self]).limit(max)
end
end
这code可能没有完全正确的,但它应该给你正确的想法。
That code might not be exactly correct, but it should give you the right idea.
此外,您可能想看看<一href="http://stackoverflow.com/questions/2150582/has-many-through-a-has-and-belongs-to-many-association">this问题要问一个潜在的替代解决方案来定义这个东西你自己。
Also, you might want to look at this question for a potential alternate solution to defining this stuff yourself.
这篇关于扶手:如何获取这是2'的has_many'级深的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!