Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert has_one_attached to has_many_attached to an exising table with has_one attachments?

I have a Message model which had

  class Message < ApplicationRecord
    has_one_attached :attachment

but now I need to convert it to :

  class Message < ApplicationRecord
    has_many_attached :attachments

to enable multiple attachments for messages So I changed has_one_attached to has_many_attached in the model Message

but when I run message.attachments.attached? it returns false to existing attachment. It works correctly for the newly attached files.

Should I be adding a migration or a one time rake task which manually adds/converts the attachments?

What is the correct way of doing this?

like image 725
grafi33 Avatar asked Oct 17 '25 06:10

grafi33


1 Answers

The reason why message.attachments.attached? returns false is because you changed the name of the attribute from attachment to attachments. ActiveStorage saves that attribute name in the DB so if that name changes in the code, it can not find the old attachments anymore.

So either you don't change the attribute name (simplest solution) or you create a data migration like this

    ActiveStorage::Attachment.where(name: "attachment")
                             .where(record_type: "Message")
                             .update(name: "attachments")
like image 99
Daniel Sindrestean Avatar answered Oct 18 '25 21:10

Daniel Sindrestean