← Back to Upcase

Where do you usually place your ActiveRecord query's eager loadings?


(Samnang Chhun) #1

I feel not sure where do I place eager loadings( includes | preload | eager_load) responsibility in my rails app. Most of the time, we need eager loadings when we display on views, but all data should load in controller action. I feel pain when I put it that responsibility in controller action because it makes the controller action not clean and hard to stub their interface when we do testing, and also it will have some duplication when we need that for multiple places. When I move that responsibility into model’s association themselves, then I don’t feel good either because I found out not all places that I call associations need to do eager loadings.

What’s your style/convention for this problem?


(rubylove.io) #2

To me an ActiveRecord only has 2 types of methods, persistence/retrieval and validations.

Everything else should be somewhere else, which means that this is exactly what should be defined, either as scopes, or class level methods on the model.

class User < ActiveRecord::Base
  # has_many ....

  def self.accounts
    joins(:accounts)
  end

  def self.companies(account_scope)
    account_scope.joins(:accounts)
  end

  def self.companies_with_address(account_scope)
    account_scope.include(:address)
  end

  def self.accounts_with_owners
    accounts.include(:owner)
  end

  def self.accounts_with_owners_and_companies_with_addresses
    account_scope = User.accounts_with_owners
    User.companies_with_address(account_scope)
  end

end

At least that is how I would do it. Does that answer your question or did I misread you?


(Samnang Chhun) #3

@Dreamr what do you name your methods when you want to do eager loading with many associations at once?


(rubylove.io) #4

I added more scopes in the example above.

I like to stick to naming shit what it is, not obfuscate it into oblivion :smile: However, I have the advantage as english is my native tongue, and so much so I have been called a ‘wordy little ^%$%#’

Hope the above extra code examples helps, obviously this all depends on your db structure and type.