Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails force models to eager load

I would like to be able to load an entire app so that I may find the descendants of a given class.

For example given I have the following class defined:

# app/models/foo_class.rb class FooClass < MySpecialBaseClass   # pasta code end 

It won't be found with:

irb> ObjectSpace.each_object.select { |obj| obj.is_a?(Class) && obj <= MySpecialBaseClass } => [] 

Until I call the const:

irb> FooClass 

Then it is returned:

irb> ObjectSpace.each_object.select { |obj| obj.is_a?(Class) && obj <= MySpecialBaseClass }   => [FooClass] 

How would I go about doing this?

like image 357
Jason Waldrip Avatar asked Nov 07 '13 15:11

Jason Waldrip


People also ask

What is conditional eager loading in rails?

Conditional Eager Loading in Rails. One of the most common performance issues that can affect a rails application (or any other web application) is the n+1 queries problem. This is usually an easy issue to solve, but there may be situations where the solution is not so trivial.

How to use eager loading with multiple queries in rails?

Typically, when you want to use the eager loading feature you would use the #includes method, which Rails encouraged you to use since Rails2 or maybe even Rails1 ;). And that works like a charm doing 2 queries:

How to preload additional data in rails?

The whole mystery is that Rails has 2 ways of preloading data. One is using separate db queries to obtain the additional data. And one is using one query (with left join) to get them all.

What is the difference between eager_load and preload?

The whole mystery is that Rails has 2 ways of preloading data. One is using separate db queries to obtain the additional data. And one is using one query (with left join) to get them all. If you use #preload, it means you always want separate queries. If you use #eager_load you are doing one query.


1 Answers

Well, after some digging, it actually is really simple. Just need to run the following.

Rails.application.eager_load! 
like image 76
Jason Waldrip Avatar answered Oct 13 '22 20:10

Jason Waldrip