Active Storage - Bulk importing files stored locally
I am adding active storage file uploading as a new feature to an existing Rails application. I have at least a couple of thousand PDF files with a standard naming format that looks like this 18-001-CUNSTOMER_NAME. The 18-001 is the file number which matches a record in my Rails app. Is there a way to create a rake task or something like that to bulk import these files which are stored on a local hard drive? The polymorphic associations are a little confusing for me.
Also, just wanted to let you know how much I appreciate your screencast & guides. They have been very helpful!!
You can definitely create a rake task for that.
What you'd need to do is decide which associated record your want your uploads with and then scan through the directory to find your files and then open then and run the
attach method like so:
@message.image.attach(io: File.open('/path/to/file'), filename: 'file.pdf' , content_type: 'application/pdf')
Roughly you'd want to do something like:
Dir["/path/to/search/*.pdf"].each do |filename| # Look up or create record you want to attach this file to. # You can use the filename to parse out the customer name, etc. # We'll assume you set it as a variable called @record. @record = Record.first @record.image.attach( io: File.open(filename), filename: File.basename(filename), content_type: 'application/pdf' ) end