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

Rails Administrate多对多多态STI关联illustrateable_type存储错误如何修复

问题根源

该问题由两个配置错误共同导致:

  1. Rails多态关联默认不会存储STI子类的完整类名,只会存储最顶层的基类名
  2. Brand模型的关联配置错误,写反了多态标识的归属

修复步骤

1. 修正多态关联的STI类名存储配置

给Illustration模型的多态关联添加store_full_sti_class: true参数,强制存储实际的子类类名:

class Illustration < ApplicationRecord
  # 新增store_full_sti_class参数
  belongs_to :illustrateable, polymorphic: true, store_full_sti_class: true
  belongs_to :brand
end

2. 修正关联配置

移除Brand模型中illustrations关联错误添加的as: :illustrateable参数,同时给Image、Video补全反向多态关联:

class Brand < ApplicationRecord
  # 移除as: :illustrateable参数
  has_many :illustrations, dependent: :destroy
  has_many :images, through: :illustrations, source: :illustrateable, source_type: 'Image'
  has_many :videos, through: :illustrations, source: :illustrateable, source_type: 'Video'
end

class Image < Medium
  has_many :illustrations, as: :illustrateable, dependent: :destroy
  has_many :brands, through: :illustrations
end

class Video < Medium
  has_many :illustrations, as: :illustrateable, dependent: :destroy
  has_many :brands, through: :illustrations
end

3. 确认强参数配置

在Admin::IllustrationsController中添加如下方法,确保illustrateable相关参数可正常写入:

def permitted_attributes
  super + [:illustrateable]
end

修改完成后重启服务再测试提交,illustrateable_type就会正常存储为选中的Image或Video子类名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:48:04