Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 includes translations globalize3 activerecord

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?

like image 821
Pioz Avatar asked Dec 02 '10 16:12

Pioz


2 Answers

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
like image 155
Michał Szajbe Avatar answered Sep 27 '22 19:09

Michał Szajbe


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
like image 42
Chris Avatar answered Sep 27 '22 19:09

Chris