Rails 3包含翻译globalize3 activerecord

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Rails 3包含翻译globalize3 activerecord相关的知识,希望对你有一定的参考价值。

我有这个架构:Post Categories_to Category和Category has_many Post。帖子和类别通过gem globalize进行全球化]

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查询问题?

答案

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

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

  default_scope includes(:translations)
end
另一答案

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 表进行简单搜索

Rails 3 - 可以使用acts_as_audited 进行设计吗?

Ruby on Rails:RSpec 和 Acts As Audited(在测试时禁用acts_as_audited?)

Rails 4:acts_as_taggable_on 的 text_field 不使用逗号分隔标签

在rails上使用select2 gem和acts_as_taggable gem

Rails Acts_as_votable Gem Like/Unlike 按钮与 Ajax