Search code examples
ruby-on-rails-3activerecordeager-loading

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)


Solution

  • You can use default_scope:

    class Comment < ActiveRecord::Base
      default_scope includes(:user)
    end
    
    Comment.first # => the same as Comment.includes(:user).first