2015-01-26 1 views
0

다음과 같은 방법과 연결은 동일한 작업을 수행합니다. 그들은 현재 학교에서 'active_students'방법을 사용할 수 있도록합니다. 그러나이 협회는 125 개의 쿼리를 사용하며이 방법은 1을 사용합니다.이 방법은 eager-loading을 사용하지만 더 많은 연관이있는 것으로 보입니다.레일 4 열심히 로딩 (연결 대 메서드) 효율성

왜 school.accounts가 계정에서 쿼리를 작성하는 것보다 비효율적입니까? 협회를 유지하고 eager-loading을 사용할 수 있습니까? 내 방식이 적절하게 접근하고 있습니까? 아니면이 방법에 접근하는 더 좋은 방법이 있습니까?

# application_controller 

    def active_students # 1 query 
    # used by simply calling active_students 
    Account.includes(:role, {user: :school}).where(status: 0).where("roles.name = ?", 'student').where("users.school_id = ?", current_school.id).references(:role, :user, :school) 
    end 

# school.rb 
    # used by calling current_school.active_students 
    # 125 queries 

    has_many :active_students, -> { joins(:role).where("roles.name = ? AND accounts.status = ?", "student", 0) }, source: :accounts, through: :users 

답변