Ask A Question

Notifications

You’re not receiving notifications from this thread.

Active Storage - Bulk importing files stored locally

Steven Little asked in Rails

Hi Chris,
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!!

Reply

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
Reply

Thank you Chris.

Reply

What if you don't specify the content_type? Will it hurt anything?

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.