我有这个架构: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 查询问题?