Rails 3 includes translations globalize3 activerecord -
i have schema: post belongs_to category , category has_many post. post , category globalize 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 postscontroller posts line of code:
def index @posts = post.includes([:translations, {:category => :translations}]) end
the problem have n+1 query problem category translations table:
post load (0.3ms) select "posts".* "posts" post::translation load (0.3ms) select "post_translations".* "post_translations" ("post_translations".post_id in (2,3,4)) # start n+1 query block category load (1.9ms) select "categories".* "categories" ("categories"."id" in (9,12,11)) category::translation load (0.4ms) select "category_translations".* "category_translations" ("category_translations".category_id = 9) , ("category_translations"."locale" in ('it')) cache (0.0ms) select "category_translations".* "category_translations" ("category_translations".category_id = 9) , ("category_translations"."locale" in ('it')) category::translation load (0.2ms) select "category_translations".* "category_translations" ("category_translations".category_id = 12) , ("category_translations"."locale" in ('it')) cache (0.0ms) select "category_translations".* "category_translations" ("category_translations".category_id = 12) , ("category_translations"."locale" in ('it')) category::translation load (0.2ms) select "category_translations".* "category_translations" ("category_translations".category_id = 11) , ("category_translations"."locale" in ('it')) cache (0.0ms) select "category_translations".* "category_translations" ("category_translations".category_id = 11) , ("category_translations"."locale" in ('it')) # end n+1 query block category::translation load (0.5ms) select "category_translations".* "category_translations" ("category_translations".category_id in (9,12,11))
how can solve n+1 query problem?
you should enable eager loading of translations in model. recommended way is:
class category < activerecord::base has_many :posts translates :name # globalize3 default_scope includes(:translations) end
Comments
Post a Comment