8

我有这个架构:Post belongs_to Category 和 Category has_many Post。Post 和 Category 使用 gem globalize3 进行全球化

class Post < ActiveRecord::Base
  belongs_to :category
  translates :title, :excerpt, :desc # globalize3
end

class Category < ActiveRecord::Base
  has_many :posts
  translates :name # globalize3
end

在我的 PostsController 中,我使用这行代码获取所有帖子:

def index
  @posts = Post.includes([:translations, {:category => :translations}])
end

问题是我对类别翻译表有 n+1 查询问题:

Post Load (0.3ms)  SELECT "posts".* FROM "posts"

Post::Translation Load (0.3ms)  SELECT "post_translations".* FROM "post_translations" WHERE ("post_translations".post_id IN (2,3,4))

# START n+1 query block
Category Load (1.9ms)  SELECT "categories".* FROM "categories" WHERE ("categories"."id" IN (9,12,11))
Category::Translation Load (0.4ms)  SELECT "category_translations".* FROM "category_translations" WHERE ("category_translations".category_id = 9) AND ("category_translations"."locale" IN ('it'))
CACHE (0.0ms)  SELECT "category_translations".* FROM "category_translations" WHERE ("category_translations".category_id = 9) AND ("category_translations"."locale" IN ('it'))
Category::Translation Load (0.2ms)  SELECT "category_translations".* FROM "category_translations" WHERE ("category_translations".category_id = 12) AND ("category_translations"."locale" IN ('it'))
CACHE (0.0ms)  SELECT "category_translations".* FROM "category_translations" WHERE ("category_translations".category_id = 12) AND ("category_translations"."locale" IN ('it'))
Category::Translation Load (0.2ms)  SELECT "category_translations".* FROM "category_translations" WHERE ("category_translations".category_id = 11) AND ("category_translations"."locale" IN ('it'))
CACHE (0.0ms)  SELECT "category_translations".* FROM "category_translations" WHERE ("category_translations".category_id = 11) AND ("category_translations"."locale" IN ('it'))
# END n+1 query block

Category::Translation Load (0.5ms)  SELECT "category_translations".* FROM "category_translations" WHERE ("category_translations".category_id IN (9,12,11))

我如何解决这个 n+1 查询问题?

4

2 回答 2

12

您应该在模型中启用即时加载翻译。推荐的方法是:

class Category < ActiveRecord::Base
  has_many :posts
  translates :name # globalize3

  default_scope includes(:translations)
end
于 2013-10-02T09:19:09.900 回答
5

Rails 4,5,6:从 Michał Szajbe 那里得到答案,稍作修改后仍然有效:

class Category < ActiveRecord::Base
  has_many :posts
  translates :name

  default_scope { includes(:translations) }
end
于 2015-12-08T10:48:04.953 回答