I am using eager loading to join two of my tables
The Model1 table has about 800 rows and has many references to other tables. Whenever that line is called, it takes about 3 minutes to load the view that shows the info.
I then tried making a straight Postgres connection and running the same SQL query that was generated from the eager load and that finished in 50ms.
Why is it taking so much longer in ActiveRecord and is there anyways I can cut down on the time?
In the console, it gets to the following SQL query (this is a simplified version, of course) and it hangs for about 3 minutes before it continues and loads the page.
SELECT model1.*, model2.* FROM model1 LEFT OUTER JOIN model2 ON model2 .foreign_key = model1.idAnswer1:
It's likely that this is not due to eager loading per se, but reflects the overhead of instantiating many model objects. ActiveRecord must initialize objects when retrieving them from a database. You can prove this to yourself by adding a callback to the associated model:
after_find :yodel def yodel puts "Yodel-a-e-hoo!" end
This is pretty fast, but it is not instantaneous. When you are getting back many objects, that initialization time will start to affect performance.
The typical solution is to paginate results if possible. Otherwise you may need to re-write the query, using raw SQL if necessary, to be more selective.