0

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
hellion
  • 4,602
  • 6
  • 38
  • 77

1 Answers1

0

@hellion, I think these blog http://blog.arkency.com/2013/12/rails4-preloading

and http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes.html can help you.

Chitra
  • 1,294
  • 2
  • 13
  • 28