问题
I am having images under app/assets/images/admin
directory.
In development I've used something like this to get the URL
"#{root_url}assets/admin/filename.jpg"
But its not working on Heroku.
So what is the best way to reference images under assets folder on Heroku?
回答1:
reference images under assets folder
If you're using image_tag, you'll be able to call the relative path regardless of whether you're in production
or development
:
<%= image_tag "admin/filename.jpg" %>
--
If you're calling the image in your CSS, you'll need to use asset-path or asset-url:
#app/assets/stylesheets/application.css
.header {
background: asset-url("admin/filename.png");
}
The problem you have is to do with asset fingerprinting.
When you precompile your assets (which is required in Heroku), all the images
, css
, javascript
etc is put into the public/assets
folder. More importantly, each file is fingerprinted (has some numbers appended to it):
global-908e25f4bf641868d8683022a5b62f54.css
Thus, calling #{root_url}assets/admin/filename.jpg
will result in a 404 when you're in "production", because the file will not exist.
You need to use one of the path helpers (above) to make sure Rails can pick out the correct file, regardless of which environment you're using.
回答2:
use image_tag('admin/filename.jpg')
to get the html with the part to the picture:
development# => <img alt="Rails" src="http://yourhost/assets/admin/filename.jpg" />
production# => <img alt="Rails" src="http://yourhost/assets/admin/filename-5643564625453543.jpg" />
use image_path("admin/filename.jpg")
to get the path like this:
development# => "/assets/admin/filename.jpg"
production# => "/assets/admin/filename-5643564625453543.jpg"
use image_url("admin/filename.jpg")
to get the full url like this:
development# => "http://yourhost/assets/admin/filename.jpg"
production# => "http://yourhost/assets/admin/filename-5643564625453543.jpg"
You can get more information on
The Assets Pipeline
Asset URL Helper
来源:https://stackoverflow.com/questions/33537887/rails-absolute-url-for-images-in-assets-path-for-heroku