ruby-on-rails – Rails 3包括翻译globalize3 activerecord

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails 3包括翻译globalize3 activerecord前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个架构:帖子belongs_to类别和类别has_many帖子.
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,11))

我如何解决这个n 1查询问题?

解决方法

您应该在模型中启用预先加载的翻译.推荐的方法是:
class Category < ActiveRecord::Base
  has_many :posts
  translates :name # globalize3

  default_scope includes(:translations)
end

猜你在找的Ruby相关文章