Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force active record (Ruby) eager loading at the model level?

We would like to force our Post model to eager load all comments.

Right now we have to specify the eager loading at the find(:all), like below:

Post.all(:include => [ :comment ])

Is there a way to force an eager loading default at the Post model level, rather than having to do it in every find? Something like below:

class Post < ActiveRecord::Base
  has_many :comments, :include <all comments>  # eager load??
like image 940
Kevin Baker Avatar asked Jan 06 '11 18:01

Kevin Baker


People also ask

What is Ruby ActiveRecord?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is Active model in Ruby?

Active Model is a library containing various modules used in developing classes that need some features present on Active Record.

What is Rails eager load?

Eager loading is a way to find objects of a certain class and a number of named associations. Here I share my thoughts on using it with Rails. What are N + 1 queries? It mainly occurs when you load the bunch of objects and then for each object you make one more query to find associated object.


1 Answers

It looks like you'll want to tweak your default_scope for this.

like image 107
girasquid Avatar answered Oct 22 '22 10:10

girasquid