I have this schema: Post belongs_to Category and Category has_many Post. Post and Category are globalize with 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
In my PostsController I get all posts with this line of code:
def index
@posts = Post.includes([:translations, {:category => :translations}])
end
The problem is that I have n+1 query problem with category translations table:
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))
How I can solve this n+1 query problem?
You should enable eager loading of translations in the model. Recommended way to do this is:
class Category < ActiveRecord::Base
has_many :posts
translates :name # globalize3
default_scope includes(:translations)
end
Rails 4,5,6: Taking the answer from Michał Szajbe this still works with a slight modification:
class Category < ActiveRecord::Base
has_many :posts
translates :name
default_scope { includes(:translations) }
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With