나는이 모델이 설정 한 :레일 : 2 'has_many'수준의 레코드를 가져 오는 방법은 무엇입니까?
Course
has_and_belongs_to_many Student
Student
has_and_belongs_to_many Course
has_many Books
Book
belongs_to Student
가 어떻게 효율적으로 액티브와 과정에 대한 모든 책을받을 수 있나요?
나는이 모델이 설정 한 :레일 : 2 'has_many'수준의 레코드를 가져 오는 방법은 무엇입니까?
Course
has_and_belongs_to_many Student
Student
has_and_belongs_to_many Course
has_many Books
Book
belongs_to Student
가 어떻게 효율적으로 액티브와 과정에 대한 모든 책을받을 수 있나요?
이 시도 :
Course.includes(:students => { :books })
문서는 "협회의 열망로드"에서, here입니다.
편집
죄송합니다, 제가 질문을 오해. 나는 당신의 초점이 주어진 과목을위한 책에 있다는 것을 알아. 이 경우 I는 다음과 같이 추천 할 것입니다 :
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
는 그 코드가 정확히 정확하지 않을 수도 있지만 당신에게 올바른 아이디어를 제공해야합니다.
또한 this 질문을보고이 자료를 직접 정의 할 수있는 잠재적 인 대체 솔루션을 찾고 싶을 수도 있습니다. 당신이 연결을 통해 사용하고 뭔가를 할 수 있다면
나는
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, Eager Loading 도움. 그래도 도서에 대한 몇 가지 특별한 제약이 있습니다. 그래서 Course.where ("courses.id =?", 2) .includes (: students, : books) .where ([ "books.published >?, 1.year.ago]). order. ("books.popularity DESC") first.books 그리고이 쿼리의 가장 큰 문제점은 책에 LIMIT를 추가 할 수 없다는 것입니다. ActiveRecord가 다음과 같은 쿼리를 생성하는 데 도움이되는 방법이 있습니까? SELECT "books". * FROM "books"WHERE "books". "student_id"IN (21, 23, 19, 17, 18, 20, 5, 22, 4) – foobar
esjd이 문제를 해결하기 위해 내 대답을 편집했습니다. 도움이되는지 알려주세요. – Luke