更新Active Storage附件文件名

时间:2018-10-23 20:26:16

标签: ruby-on-rails ruby-on-rails-5 rails-activestorage

我想知道如何更新Active Storage附件的文件名。

这就是我现在正在尝试的内容:

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

如您所见,我正在尝试的方法不起作用。如何更改文件名?

1 个答案:

答案 0 :(得分:1)

我知道了:

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