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?
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With