Sql Rails:如何获取深度为2级的记录?
我设置了以下模型:Sql Rails:如何获取深度为2级的记录?,sql,ruby-on-rails,activerecord,Sql,Ruby On Rails,Activerecord,我设置了以下模型: 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 }) 在关联的快速加载下,文档被删除 编辑 对不起,我误解了这个问
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.includes(:students => { :books })
在关联的快速加载下,文档被删除
编辑
对不起,我误解了这个问题。我知道你的注意力集中在某门课程的书本上。在这种情况下,我建议如下:
Book.includes(:student => :courses).where(["course.id = ?", @course.id]).limit(5)
在课程模型中添加此方法可能更容易:
该代码可能并不完全正确,但它应该为您提供正确的想法
另外,您可能想看看这个问题,寻找一个潜在的替代解决方案来自己定义这个东西 我想知道你是否可以利用一个通联,做一些像
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,它将返回与课程相关的所有书籍。我想知道您是否可以使用直通关联并执行类似于
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,它将返回与课程相关的所有书籍。谢谢Luke,热心的加载帮助。不过,我对书籍有一些特殊的限制,因此我最终得到了如下结果:Course.wherecourses.id=?,2.includes:students,:Books.where[Books.published>?,1.year.ago].orderbooks.popularity DESC.first.Books。这个查询的最大问题是我无法为书籍添加限制。ActiveRecord有没有一种方法可以帮助我构造一个如下所示的查询?选择书籍。*从books WHERE books.student_id在21,23,19,17,18,20,5,22,4esjd中我编辑了我的答案以更好地解决此问题,如果有帮助请告诉我。感谢Luke,热心加载帮助。不过,我对书籍有一些特殊的限制,因此我最终得到了如下结果:Course.wherecourses.id=?,2.includes:students,:Books.where[Books.published>?,1.year.ago].orderbooks.popularity DESC.first.Books。这个查询的最大问题是我无法为书籍添加限制。ActiveRecord有没有一种方法可以帮助我构造一个如下所示的查询?选择书籍。*从books WHERE books.student_id在21、23、19、17、18、20、5、22、4esjd中编辑我的答案以更好地解决此问题,如果有帮助,请告诉我。