6

I'm trying to send an email attachment using action mailer in ruby on rails and I keep getting this error. The problem seems to be that it can't locate the file in the directory I specified, but the file path is valid. I also checked this using File.exist? in the console and confirmed that the path provided evaluates to true.

Here is my mailer:

class OrderMailer < ApplicationMailer   
  def purchase(order)
    @order = order
    attachments[ 'files.zip'] = File.read(Rails.root + '/public/albums/files.zip')
    mail to: order.email, subject: "Order Confirmation"
  end
end

I also installed the mail gem to handle encoding, as advised by the Action Mailer documentation.

Any help would be much appreciated, -Brian

bdowe
  • 61
  • 1
  • 1
  • 3

2 Answers2

10

Rails.root returns a Pathname object. Pathname#+(string) will File.join the string to the path if it is relative; if string represents an absolute path (i.e. starts with a slash), the path gets replaced.

Pathname.new('/tmp') + 'foo'
# => #<Pathname:/tmp/foo> 
Pathname.new('/tmp') + '/foo'
# => #<Pathname:/foo> 

This means, you are reading from the wrong path: you wanted to read /path/to/app/public/albums/files.zip, but you are actually reading /public/albums/files.zip, which likely shouldn't exist.

Solution: make sure you are appending the relative path:

Rails.root + 'public/albums/files.zip'
Amadan
  • 191,408
  • 23
  • 240
  • 301
-1

Rails.root returns path object. So you need toconvert it to string to concatenate it with another string as follows: (Rails.root.to_s + '/public/albums/files.zip')