Nima Izadi
Nima Izadi

Reputation: 1004

How to persist a tempfile between two actions

My app is on Heroku and I'm creating resources from the import of an Excel

Users of my app can import contacts from an Excel spreadsheet. The process of doing an import has multiple steps, to make it easier on the user's brain. In the first step, they upload a file (the spreadsheet). In the second step, they choose some options to process the file. These two steps can't be combined into one, because the options are dependent on the header of the file.

Right now, this is done as two actions: a POST to upload the file, and then another POST to upload the user's choices. The file, which is instanciate as a Tempfile, is not being persisted across the actions.

So, I don't want the user to upload the first file again in the intermediary action. Is this possible?

First step:

= simple_form_for [:choose_headers, @contact_import] do |f|
  = f.input :file, as: :file
  = f.submit

In this second step, the file is not persisted:

= simple_form_for [@contact_import] do |f|
  = f.input :file, as: :file
  = f.input :some_other_input
  = f.submit

Upvotes: 2

Views: 452

Answers (1)

Alex D
Alex D

Reputation: 30445

Don't use a Tempfile. Generate your own unique filename for the uploaded data, and save the file in a special directory. (If you are using Capistrano for deployment, I would put the upload directory under shared when deployed in production. In config/deploy.rb, I would add a deploy hook which creates the upload directory if it doesn't already exist. Then I would specify the relative path of the upload directory using a config value in config/environments/production.rb and config/environments/development.rb, so everything works seamlessly in both dev and production. In my controller actions, I would do something like File.join(Rails.root, UPLOAD_PATH, filename) to build the correct path for an uploaded file.)

Save the generated filename in your database, and retrieve it when the user comes back for the second step. Also, add a custom rake task which cleans up old uploads which were never used, and in production, run that task from a cron job. (I recommend using the whenever gem for configuring your cron jobs.)

Upvotes: 3

Related Questions