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

如何用单条SQL结合Mobility表后端预加载模型实例?

解决方案

核心思路

借助Mobility的表后端特性,直接在查询中关联翻译表,指定固定locale并同时筛选主表与翻译表字段,让Active Record通过单条SQL加载所有数据并生成模型实例,避免额外查询。

具体实现代码

假设翻译表为Mobility默认命名的content_translations,主表为contents,需查询的翻译字段为title、body,固定locale为:en:

Content.joins(:translations)
       .where(content_translations: { locale: :en, slug: "目标slug值" })
       .select("contents.*, content_translations.title, content_translations.body")
       .first

关键细节

  • joins(:translations):主动关联翻译表,确保单条SQL完成关联查询
  • where(content_translations: { locale: :en, slug: "目标slug值" }):同时锁定locale和slug条件,精准定位目标记录
  • select("contents.*, content_translations.title, content_translations.body"):明确选择主表全字段与所需翻译字段,Mobility会自动将这些字段映射为模型的翻译属性
  • first:获取单个实例,匹配通过slug查找的需求

验证生成的SQL

执行上述代码后,生成的SQL示例如下,确认为单条查询:

SELECT contents.*, content_translations.title, content_translations.body 
FROM "contents" 
INNER JOIN "content_translations" ON "content_translations"."content_id" = "contents"."id" 
WHERE "content_translations"."locale" = $1 AND "content_translations"."slug" = $2 
LIMIT $3

返回的Content实例会包含指定locale下的title、body等翻译属性,无需额外触发查询。

注意事项

  • 若翻译表为自定义命名,需替换joins和where中的表名为实际名称
  • 确保slug字段存在于翻译表中(符合通过翻译后的slug查找内容的需求)
  • 如需加载更多翻译字段,在select语句中追加即可,比如content_translations.meta_description

内容的提问来源于stack exchange,提问作者Sébastien Dubois

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:18:29