使用 Rails 7
我正在使用单表继承 (STI) 来存储一些非常简单的关联。源对象使用 has_many 与 STI 模型的关联。按照https://stackoverflow.com/a/45681641/1014251中的一些建议,我在连接模型中使用了多态关系。这确实很有效,但有一个烦恼:
创建连接模型时,源类型取自根 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 并且不指定系统,则detailable_source
系统会插入“Detail”而不是“Theme”:
guidance_detail = GuidanceDetail.create(guidance: Guidance.first, detailable: Theme.first)
guidance_detail.detailable_type => "Detail"
可详细显示的类型应为“主题”。
为了解决这个问题,目前我每次创建新的 GuidanceDetail 时都必须指定 detailable_type。
无效的修复
我曾尝试直接指定子对象的 has_many 关联,但得到相同的结果:
class Theme < Detail
has_many :guidance_details, as: :detailable
end
替代创建方法不起作用
theme = Theme.first
guidance = Guidance.first
guidance.themes << theme
输出:
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"]]
如您所见:“detailable_type”是“Detail”。