You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails使用Mobility gem预加载模型集合多语言翻译解决N+1问题

解决方案

Mobility 的 table 后端原生支持翻译内容预加载,两种常用方案可解决 N+1 查询问题:

方案1:调用内置预加载方法直接查询

修改原查询语句,调用 Mobility 提供的 with_translations 方法即可一次性预加载所有关联 Employee 对应的翻译内容:

# 预加载当前 I18n.locale 对应的翻译
Company.first.employees.with_translations.map(&:job_function)

# 如需预加载多个语种的翻译,可指定对应的 locale 参数
Company.first.employees.with_translations(:en, :'zh-CN').map do |employee|
  [employee.job_function_en, employee.job_function_zh_cn]
end

该方案适合仅查询单个 Company 下关联员工的场景,会自动过滤非目标 locale 的翻译数据,查询效率更高。

方案2:嵌套预加载关联

如果是批量查询多个 Company 及其关联员工的场景,可以直接预加载 Mobility 自动生成的 translations 关联,和 Rails 原生关联预加载逻辑完全一致:

# 一次性预加载所有 Company、关联 Employee 及对应的翻译内容
Company.includes(employees: :translations).find_each do |company|
  company.employees.map(&:job_function)
end

该方案兼容性更强,支持多层级嵌套预加载的复杂查询场景。


内容的提问来源于stack exchange,提问作者Mladen Danic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:24:04