foobar
foobar

Reputation: 11384

Rails: How to fetch records that are 2 'has_many' levels deep?

I have these models set up:

Course
  has_and_belongs_to_many Student

Student
  has_and_belongs_to_many Course
  has_many Books

Book
  belongs_to Student

How do I efficiently get all the Books for a Course with ActiveRecord?

Upvotes: 2

Views: 4851

Answers (2)

Mark Locklear
Mark Locklear

Reputation: 5355

I wonder if you could use a through association and do something like...

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

Now you can call Course.books which would return all books associated with a course.

Upvotes: 3

Luke
Luke

Reputation: 4925

Try this:

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

Documentation is here, under "Eager loading of associations".

Edited

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)

It would probably be easier to add this as a method on the Course model:

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

That code might not be exactly correct, but it should give you the right idea.

Also, you might want to look at this question for a potential alternate solution to defining this stuff yourself.

Upvotes: 6

Related Questions