Skip to content

How to save the uploaded file name with carrierwave_direct and S3

So you’ve setup carrierwave_direct and you’re happily uploading files to Amazon S3. In this example I’ve mounted CarrierWave on a field called csv_file, but that can be whatever is appropriate to your app.  

You’ve probably got two controller methods

def upload
  @model = Model.new
  @model.save

  @uploader = @model.csv_file
  @uploader.success_action_callback = upload_successful_model_url(@model)
end

def upload_successful
  @model = Model.find(params[:id])

  # Now what??
end

You need to save the file name to the model so that it can be referenced later. The documentation (at the time of writing) offers no indication of how you might go about that. The secret is in the key attribute that CarrierWave adds to your model.

def upload_successful
  @model = Model.find(params[:id])
  @model.key = params[:key]
  @model.save

  redirect_to model_path(@model)
end

Simple. When you know how!