1

これらのモデルをセットアップしました:

Course
  has_and_belongs_to_many Student

Student
  has_and_belongs_to_many Course
  has_many Books

Book
  belongs_to Student

ActiveRecord を使用してコースのすべての本を効率的に取得するにはどうすればよいですか?

4

2 に答える 2

6

これを試して:

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

このコードは正確ではないかもしれませんが、正しい考えが得られるはずです。

また、このようなものを自分で定義するための潜在的な代替ソリューションについて、この質問を見たいと思うかもしれません。

于 2012-10-24T01:16:37.660 に答える
3

スルーアソシエーションを使用して、次のようなことを行うことができるでしょうか...

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を呼び出すことができます。

于 2012-10-25T13:02:30.057 に答える