The following method and association accomplish the same thing. They both make an 'active_students' method available to the current school. However, the association uses 125 queries, and the method uses 1. The method uses eager-loading but, the association seems more the rails way to do it.
Why is school.accounts so inefficient compared to building the query off of Account? Is it possible to keep the association and use eager-loading on it? Is my method approach appropriate, or is there a better way to approach this?
# 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
vs
# 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