如何始终包含急切加载的模型

Nic*_*nto 4 activerecord eager-loading ruby-on-rails-3

我使用bullet gem让我知道N + 1个查询.

我想避免偶尔添加include.

我有一个comment属于user模型的模型

有没有办法告诉模型任何时候访问评论模型以包括用户?(而不是Comment.include(:user)每次都做)

kul*_*esa 9

你可以使用default_scope:

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

Comment.first # => the same as Comment.includes(:user).first
Run Code Online (Sandbox Code Playgroud)