简体   繁体   中英

How do I get the base URL (e.g. http://localhost:3000) of my Rails app?

I'm using Paperclip to allow users to attach things, and then I'm sending an email and wanting to attach the file to the email. I'm trying to read the file in and add it as an attachment, like so:

# models/touchpoint_mailer.rb
class TouchpointMailer < ActionMailer::Base
  def notification_email(touchpoint)
    recipients "me@myemail.com"
    from "Touchpoint Customer Portal <portal@touchpointclients.com>"
    content_type "multipart/alternative"
    subject "New Touchpoint Request"
    sent_on Time.now
    body :touchpoint => touchpoint

    # Add any attachments the user has included
    touchpoint.assets.each do |asset|
      attachment :content_type => asset.file_content_type,
                 :body => File.read(asset.url)
    end
  end
end

This gives me the following error No such file or directory - /system/files/7/original/image.png?1254497688 with the stack trace saying it's the call to File.read . When I visit the show.html.erb page, and click on the link to the image, which is something like http://localhost:3000/system/files/7/original/image.png?1254497688 , the image is displayed fine.

How can I fix this problem?

Typically root_url should provide this.

File.read is expecting a file path, not a url though. If you are generating the images, you should call the image generating code and return the bytes of the generated image instead of calling File.read(…)

request.env["HTTP_HOST"]

I don't know why this one line of code is so elusive on the web. Seems like it should be up front and center.

asset.url returns the URL to the file. This is usually /system/classname/xx/xx/style/filename.ext . You'd put this in an image_tag .

You want asset.path . It returns the full path to the file, which will usually be something like /home/username/railsapp/public/system/classname/xx/xx/style/filename.ext

HTH.

as ZiggyTheHamster is saying: the asset.url is the generated url that would be used on webpages (which is why you're getting the unix-style directory slashes, as pointed out in the comments.)

asset.path should give you the OS-aware path to the file, but even that isn't needed with paperclip. Paperclip::Attachment is already an IOStream.

You just need :body => asset like so:

touchpoint.assets.each do |asset|
  attachment :content_type => asset.file_content_type,
             :body => asset
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM