gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:21:36 27 4
gpt4 key购买 nike

我有这样的架构:发布所属类别和类别 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,12,11))

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

最佳答案

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

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

default_scope includes(:translations)
end

关于ruby-on-rails - Rails 3 包括翻译 globalize3 activerecord,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4337086/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com