나는이 스키마를 가지고 있습니다 : 게시 belongs_to 카테고리와 카테고리 has_many 포스트. 포스트 및 카테고리 내가 PostsController에서 보석 globalize3레일즈 3 번역을 포함합니다. globalize3 activerecord
class Post < ActiveRecord::Base
belongs_to :category
translates :title, :excerpt, :desC# globalize3
end
class Category < ActiveRecord::Base
has_many :posts
translates :name # globalize3
end
와 세계화 있습니다 나는 코드 줄에 모든 게시물 수 :
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 쿼리 문제를 해결할 수 있습니까?