← Back to Upcase

Need help understanding where/when eager loading is 'used'


(Jarrett Green) #1

I realize if I have Post model that belongs to a category, and I want to display them in a table, I can eager load in the controller to include the post’s category. No problem.

I have a model, however, that does a lot of calculations based of an associated model’s attributes. i.e.

  def current_wages_annualized
  if archived_current_wages.nil?
    employee.annual_salary
  else
    employee.annual? ? current_wages : current_wages * employee.work_hours_in_a_year
  end  
end

def new_wages_annualized
  if employee.hourly?
    new_wages*(employee.work_hours_in_a_week*52)
  else
    new_wages
  end
end

Those were the least ugly expamples I could find. Lol. Anyway - this model belongs_to employee - it appears that every time this model calls employe.any_method it fetches it from the db - tons of times. Is there a way to ‘cache’ employee in the my model - maybe through an instance var so it only calls it once or am I just not understanding how eager loading should work?

edit: Here are all the necessary includes - no whining from bullet with these.

    @scenario = @current_company.scenarios.includes(:merit_increase_matrix[:matrix_rows => :performance_level], :scenario_entries => [:manual_scenario_entry, :scenario, :employee => [:midpoint, :branch => [:location], :position => [:department]]]).find(params[:id])

@merit_increase_matrix = @scenario.merit_increase_matrix

@scenario_entries = @scenario.scenario_entries

(Jarrett Green) #2

I think what was causing a ton of problems was a few default_scopes to order branch, location, company, etc. Took those out and brought my total queries down.