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

Rails 7中带多态关联的STI through模型自动填充source_type为父类而非实际子类的问题

Rails 7中带多态关联的STI through模型自动填充source_type为父类而非实际子类的问题

我在Rails 7里做开发,用单表继承(STI)来处理一些简单的关联关系。源对象和STI模型之间用has_many关联,之前参考了相关建议在中间关联模型里用了多态关系,整体运行都挺顺畅,但有个烦人的小问题:创建中间关联模型时,系统会自动把源类型设为STI的根类,而不是实际使用的子类。

模型代码

先贴一下我用到的几个核心模型:

class Guidance < ApplicationRecord
  has_many :guidance_details
  has_many :themes, through: :guidance_details, source: :detailable, source_type: "Theme"
end

class Detail < ApplicationRecord
  has_many :guidance_details, as: :detailable
  has_many :guidances, through: :guidance_details
end

class GuidanceDetail < ApplicationRecord
  belongs_to :detailable, polymorphic: true
  belongs_to :guidance
end

class Theme < Detail
end

问题详情

当我创建新的GuidanceDetail时,即使传入的是Theme实例,系统自动填充的detailable_type会是父类Detail,而不是预期的Theme。举个例子:

guidance_detail = GuidanceDetail.create(guidance: Guidance.first, detailable: Theme.first)
guidance_detail.detailable_type => "Detail"

现在我只能每次创建时手动指定detailable_type才能绕开这个问题,但这显然不是最优解。

尝试过的无效解决方法

我试过两种思路,但都没能解决问题:

1. 在子类中直接定义关联

我想着在Theme子类里显式定义关联,会不会让系统识别到正确的类型,结果还是一样:

class Theme < Detail
  has_many :guidance_details, as: :detailable
  has_many :guidances, through: :guidance_details
end

创建关联时,detailable_type依然被设为"Detail"。

2. 通过关联关系间接创建

我还试了通过Guidance的themes关联来间接生成中间记录,比如:

theme = Theme.first
guidance = Guidance.first

guidance.themes << theme

但数据库执行的插入语句里,detailable_type还是"Detail",对应的SQL日志如下:

GuidanceDetail Create (1.3ms)  INSERT INTO "guidance_details" ("detailable_id", "guidance_id", "position", "created_at", "updated_at", "detailable_type") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"  [["detailable_id", 11], ["guidance_id", 1], ["position", nil], ["created_at", "2024-11-14 10:24:19.785623"], ["updated_at", "2024-11-14 10:24:19.785623"], ["detailable_type", "Detail"]]

备注:内容来源于stack exchange,提问作者ReggieB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 10:14:30