Anuja
Anuja

Reputation: 51

undefined method `original_filename' for nil:NilClass

I'm trying to upload a file to an email as attachment.When i try to upload, i have an error

"undefined method `original_filename' for nil:NilClass" What i'm doing wrong?

I need to catch the file from the controller,and handle the exception if params[:file] not present?

In my view, there's simple upload file tag

%strong Send Email with PDF attachment:
      = file_field_tag :file

I need to catch the file from the controller, This is my controller..

 @name = params[:file].original_filename
        if params[:file].present?
          directory = "public/data"
          path = File.join(directory, @name)
          uniq_name = (0...10).map {(65 + rand(26)).chr}.join
          time_footprint = Time.now.to_formatted_s(:number)

          File.open(path, "wb") do |file|
            file.write(params[:file].read)
            @uniq_path = File.join(directory, uniq_name + time_footprint + File.extname(file))
            File.rename(file, @uniq_path)
          end
        else
          flash[:notice] = "You are going to send email without the invoice"
          redirect_to update_estimate_job_final_invoices_path(@ticket)

        end

Upvotes: 1

Views: 793

Answers (1)

infused
infused

Reputation: 24337

The first line is @name = params[:file].original_filename. If params[:file] is not present then the call to original_filename will fail. Move that line inside the if statement:

if params[:file].present?
  @name = params[:file].original_filename
  directory = "public/data"
  path = File.join(directory, @name)
  ...
else
  ...
end

Upvotes: 1

Related Questions