ActiveStorage "id delegated to attachment, but attachment is nil"

ActiveStorage "id delegated to attachment, but attachment is nil"

我正在从使用 Paperclip 迁移到现在使用 ActiveStorage。 我已经 运行 完成了提供的迁移指南 here

我有一个 Logo 模型和一个 School 模型。

一个Schoolhas_one_attached :logo和一个Logobelongs_to :school

在控制台中,

school = School.find(119)
school.logo.id

# returns this error :: 
Module::DelegationError Exception: id delegated to attachment, but attachment is nil

获取 运行 的基础查询如下所示(这就是问题所在),

SELECT  "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" =  AND "active_storage_attachments"."record_type" =  AND "active_storage_attachments"."name" =  LIMIT   [["record_id", 119], ["record_type", "School"], ["name", "logo"], ["LIMIT", 1]]

我不明白为什么查询在 ACTIVE_STORAGE_ATTACHMENTS table 中搜索具有 School record_typerecord_id 的记录我的 School 对象。它应该在 table 中搜索 Logo 类型和我的 Logo 对象的 id

在我的数据库中,我确实有一个 Logo 记录,并且该记录的 ID 映射到 ACTIVE_STORAGE_ATTACHMENTS table 和该记录的 record_id 列有一个 blob_id 映射到 ACTIVE_STORAGE_BLOBS table 上的 id 列并且包含正确图像的信息。

所以看起来数据方面的一切都是正确的。

有谁知道为什么正在执行的基础 SQL 查询正在寻找错误的 typeid,导致 id delegated to attachment, but attachment is nil 错误?

根据冗长的聊天,答案是您的遗留模型结构 (School + Logo) 与迁移指南中假定的模型结构 (User) 不平行只要)。因此,您不能简单地复制并粘贴所提供的脚本并期望它成功 运行。

要成功迁移到 ActiveStorage,您需要修改迁移指南中提供的脚本以适应您的特定模型结构。