我有一个Genre
模型,它的名字在genre_translations表中翻译(使用globalize gem)
我正在尝试使用elasticsearch-rails gem
索引模型def as_indexed_json(options = {})
as_json(
only: %i(type available),
methods: %i(name),
)
end
但当我Genre.import
时,我在rails控制台上获得以下内容:
[1] pry(main)> Genre.import
Genre Load (27.1ms) SELECT "genres".* FROM "genres" ORDER BY "genres"."id" ASC LIMIT 1000
Genre::Translation Load (23.9ms) SELECT "genre_translations".* FROM "genre_translations" WHERE "genre_translations"."genre_id" = $1 [["genre_id", 1]]
Genre::Translation Load (0.3ms) SELECT "genre_translations".* FROM "genre_translations" WHERE "genre_translations"."genre_id" = $1 [["genre_id", 2]]
Genre::Translation Load (0.3ms) SELECT "genre_translations".* FROM "genre_translations" WHERE "genre_translations"."genre_id" = $1 [["genre_id", 3]]
...
有关如何使用联接索引所有Genre
项以避免N + 1行为的任何建议吗?
答案 0 :(得分:2)
来自文档here
# @example Pass an ActiveRecord query to limit the imported records
#
# Article.import query: -> { where(author_id: author_id) }
所以你可以这样做:
Genre.import query: -> { includes(:translations) }