Rails - absolute URL for images in assets path for heroku

感情迁移 提交于 2020-03-28 06:59:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!