Search code examples
ruby-on-railspapercliprails-activestorage

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


I'm in the process of migrating from using Paperclip to now using ActiveStorage. I've ran through the migration guide provided here.

I have a Logo model and a School model.

A School has_one_attached :logo and a Logo belongs_to :school

In the console,

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

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

The underlying query that gets ran looks like this (this is the problem),

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

I don't understand why the query is searching the ACTIVE_STORAGE_ATTACHMENTS table for a record that has a School record_type and the record_id of my School object. It should be searching that table for a Logo type and the id of my Logo object.

In my DB, I do have a Logo record and the id of that record is mapped to the record_id column of the ACTIVE_STORAGE_ATTACHMENTS table and that record has a blob_id which maps to the id column on the ACTIVE_STORAGE_BLOBS table and that contains the info for the correct image.

So it seems like everything data wise is correct.

Does anyone know why the underlying SQL query that is being executed is looking for the wrong type and id, resulting in the id delegated to attachment, but attachment is nil error?


Solution

  • Based on a lengthy chat, the answer is that your legacy model structure (School + Logo) is not parallel to the model structure assumed in the migration guide (User only). Therefore, you cannot simply copy-and-paste the script as provided and expect it to run successfully.

    To successfully migrate to ActiveStorage, you will need to modify the script provided in the migration guide to suite your particular model structure.