Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 absolute URL to an image

I'm using Rails 3.1. I'm trying to figure this out, and to my surprise, it is starting to seem that rails does not come with this method at all. Maybe im wrong.

Can anyone show how I can get a full absolute URL to an image?

I use asset_path(image.png) which gives me the relative path to use within the app. I tried doing a root_url + asset_path(image.png) but that just gives me a http://localhost:3000//assets/image.png with the double slashes

Anyone have an efficient way of doing this?

like image 867
alik Avatar asked Sep 29 '11 12:09

alik


3 Answers

See the Using asset hosts section in the documentation. You need to specify an asset_host. You can also construct it dynamically from the request chaining "#{request.protocol}#{request.host_with_port}"

like image 58
Simone Carletti Avatar answered Sep 18 '22 21:09

Simone Carletti


put this in application_helper.rb

def asset_url asset
  "#{request.protocol}#{request.host_with_port}#{asset_path(asset)}"
end

then you can use asset_url in your views.

like image 39
greggreg Avatar answered Sep 19 '22 21:09

greggreg


For Rails 4, and maybe earlier, use:

config.action_mailer.asset_host = 'https://assets.com'

per https://github.com/fphilipe/premailer-rails/issues/16

like image 38
Luke W Avatar answered Sep 18 '22 21:09

Luke W