yusefu
yusefu

Reputation: 144

Ruby On Rails: How to check if a csv file is downloaded

I have a download button in my view form, which use an "index" action in the controller

def index
  respond_to do |format|
    format.html { @some_variables = some_variables.page(params[:page]) }
    format.csv {
      render csv: some_variables, headers: SomeVariable.csv_headers
    }
  end
end

And some def self.to_csv method in my model SomeVariable, in which I generate the CSV file.

Is there anyway to check if the download was OK and for example set a flag. if download went OK do something else raise some error end

I thought about "begin rescue" in a index action, but if there is any other "smarter" implementation sharing it would be more than appreciated.

Upvotes: 0

Views: 997

Answers (2)

yusefu
yusefu

Reputation: 144

I figured out a simple solution, I opted for an after_action. after_action is run only if the action before succeeds, and in this case I'm trying to do something if the download was executed i.e if the csv render get a 202. So the if the action index is executed after that I run a method for example updating the downloaded time.

class SomeVariableController < ApplicationController

after_action :update_downloaded_time, only: :index, if: -> {current_user.admin?}

def index
  respond_to do |format|
    format.html { @some_variables = some_variables.page(params[:page]) }
    format.csv {
      render csv: some_variables, headers: SomeVariable.csv_headers
    }
  end
end

def update_downloaded_time
  @some_varibale.update_all(downloaded_at: Time.now)
end

Upvotes: 0

Stephane Paquet
Stephane Paquet

Reputation: 2344

send_file can be a good alternative to what you're planning to do. You can find more information here How to download file with send_file? and at the API Dock

Upvotes: 1

Related Questions