Rails 3 包括翻译 globalize3 activerecord

Posted

技术标签:

【中文标题】Rails 3 包括翻译 globalize3 activerecord【英文标题】:Rails 3 includes translations globalize3 activerecord 【发布时间】:2011-05-19 05:39:06 【问题描述】:

我有这个架构:Post belongs_to Category 和 Category has_many Post。 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,12,11))

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

【问题讨论】:

【参考方案1】:

您应该在模型中启用即时加载翻译。推荐的方法是:

class Category < ActiveRecord::Base
  has_many :posts
  translates :name # globalize3

  default_scope includes(:translations)
end

【讨论】:

【参考方案2】:

Rails 4,5,6:从 Michał Szajbe 那里得到答案,稍作修改后仍然可以使用:

class Category < ActiveRecord::Base
  has_many :posts
  translates :name

  default_scope  includes(:translations) 
end

【讨论】:

以上是关于Rails 3 包括翻译 globalize3 activerecord的主要内容,如果未能解决你的问题,请参考以下文章

在 Rails 中对 Globalize3 表进行简单搜索

如何使用 i18n 和 rails 配置语言环境别名?

Rails 遗留应用程序和 Ruby 2 错误:无法从文件类型 yml 加载翻译未知

Rails 3.1 资产预编译 - 包括所有 javascript 文件

英语rails怎么翻译?

Rails 页面在每次刷新时更改翻译