At which point is good to make all queries on a large project to eager load all of the objects associations?
Let me explain the background of this question.
Currently i am working on a project that has become quite complex in terms of models and associations. I started to check the server logs and saw that some views were taking some time to load because of the nested objects contained in the queries.
So i begin to refactor some of these queries to something like this:
@process = current_account.processes.query(params)
To this:
@process = current_account.processes.includes(:messages, :parts, :people).query(params)
The result was pretty good. In some views i was able to reduce the view render time and activerecord query time by 70%.
Man i was happy, so i decided to make more. But after this decision, i started to notice that not all places i refactored the code, the changes were good. In fact, there were queries that became slower.
To explain a little more about the problem i have a model like this:
class Process
has_many :anotations
has_many :publications
has_many :movimentations
has_many :reunions
has_many :profiles
...
And each one of these nested models inside process
belongs_to :user
that created it like this:
class Anotation
belongs_to :user
class Reunion
belongs_to :user
class Profile
belongs_to :user
And it go on.
In my show view
of process
, there is several tabs that display all of these nested objects and the name of the user that has added it to the current process.
With a query like this:
@process = current_account.processes.query(params)
It was performing kinda slow. So i tried something like this:
@process = current_account.process.includes(:anotations, :publications, :movimentations,
:reunions, :profiles, :messages).query(params)
This has made me gain speed on the view rendering, but in activerecord, the the time to retrieve these objects have increased significantly. And it raised to the skies when i eager loaded the user
object inside of all nested models of process
like this:
@process = current_account.process.includes({:anotations => [:user]},
{:publications => [:user], etc...).query(params)
Well, refactoring the design of the app to behave differently with these associations is not going to happen, so i ask the question again.
At which point is good to make all queries on a large project to eager load all of the objects associations?
Any tips/best practices/experience on the subject would be gladly appreciated.