Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to always include a model for eager loading

I use the bullet gem to let me know of N+1 queries.

I want to avoid adding include sporadically.

I have a comment model which belongs to a user model

Is there a way to tell the model that anytime a comment model is being accessed to include the user as well? (instead of doing Comment.include(:user) everytime)

like image 490
Nick Ginanto Avatar asked Dec 21 '22 12:12

Nick Ginanto


2 Answers

You can use default_scope:

class Comment < ActiveRecord::Base
  default_scope includes(:user)
end

Comment.first # => the same as Comment.includes(:user).first
like image 52
kulesa Avatar answered Jan 09 '23 07:01

kulesa


You should do

class Comment < ActiveRecord::Base
  default_scope { includes(:user) }
end
like image 36
helpse Avatar answered Jan 09 '23 07:01

helpse