Update Active Storage attachment filename

余生长醉 提交于 2020-06-26 12:40:30

问题


I want to know how to update the filename of an Active Storage attachment.

Here's what I'm trying now:

2.5.1 :052 > attachment.filename                                                                                                                                                             
 => #<ActiveStorage::Filename:0x00007fb2926cf6a0 @filename="example.pdf">
# at this point the filename is example.pdf

2.5.1 :053 > attachment.update!(filename: 'foo.pdf')                                                                                              
   (0.2ms)  BEGIN                                                        
  Patient Load (0.5ms)  SELECT  "patients".* FROM "patients" WHERE "patients"."deleted_at" IS NULL AND "patients"."id" = $1 LIMIT $2  [["id", 40861], ["LIMIT", 1]]
   (0.2ms)  COMMIT                                                                                                                                                                           
 => true
# I update the filename to "foo.pdf" and the save is evidently successful

2.5.1 :054 > attachment.reload.filename                                                                                                                                                      
  ActiveStorage::Attachment Load (0.4ms)  SELECT  "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."id" = $1 LIMIT $2  [["id", 99], ["LIMI
T", 1]]                                                                                                                                             
  ActiveStorage::Blob Load (0.3ms)  SELECT  "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", 99], ["LIMIT", 1]]
 => #<ActiveStorage::Filename:0x00007fb292675308 @filename="example.pdf">   
# I reload the attachment and the filename reverts to what it was before

As you can see, what I'm trying isn't working. How can I change the filename?


回答1:


I figured it out:

attachment = ActiveStorage::Attachment.find(attachment_id)
attachment.blob.update!(filename: 'new_filename.pdf')


来源:https://stackoverflow.com/questions/52957348/update-active-storage-attachment-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!