Chong Hui
Chong Hui

Reputation: 163

Renaming file before saving in ActiveStorage - Rails 5.2

I'm trying to rename a user uploaded file before saving in ActiveStorage and I don't seem to find any docs to do that. Hopefully someone has successfully done it and has code examples to share.

Thank you.

Upvotes: 4

Views: 2059

Answers (2)

Mahan Mashoof
Mahan Mashoof

Reputation: 169

This method in the model works for me:

class Model < ApplicationRecord
has_one_attached :anything

  before_save do
    if self.anything.attached?
        ext = '.' + self.anything.blob.filename.extension
        self.anything.blob.update(filename: 'desired_file_name' + ext)
    end
  end
end

Upvotes: 2

Andres23Ramirez
Andres23Ramirez

Reputation: 657

You can try the following method

@message.image.attach(io: File.open('/path/to/file'), filename: 'file.pdf')

in the official ActiveStorage documentation you can find more examples

Upvotes: 4

Related Questions