简体   繁体   中英

Heroku Image URL change

I'm developping a Rails4 application with heroku hosting, and i encounter a bit of a problem: I have a helper method to randomly pick an image by its path in /assets/images/path_to_image and this helper method is called in my HAML file. It works perfectly in my local environment. The images urls are stored in the DB. The problem is that Heroku changes the image names from logo.jpg to logo-a6d14b20c77aa6466e616313edcd3d34.jpg which makes my helper method useless. Any idea on how i could solve this problem? Is it a matter of pre-compiling the assets ? Thanks a lot B.

Is it a matter of pre-compiling the assets?

Yes, I would say so


The problem you've got is that production environments compile all your assets, and consequently give you the hashed file-name you're seeing. The reason why this is a problem is that if you're referencing a static file (logo.png) in CSS or HTML, the compiled path will be different, causing the problem to occur. We learnt if you're going to reference any assets, always use a dynamic file (.scss / .haml / .html.erb) and then use the provided helpers

The way around this is to use the asset path helpers , which are basically like this:

image_path
asset_path

Heroku

It seems you're well versed with Rails so I don't bore you with the details

Heroku works best by serving static assets & pre-compiling them before you deploy:

#config/production.rb
config.serve_static_assets = true

You then need to pre-compile the assets with the production environment, like this:

> rake assets:precompile RAILS_ENV=production

This goes through your assets & assigns all the correct paths, if you've used the asset path helpers as mentioned above. After that, push to heroku & I always pre-compile the assets when on Heroku too (we use the asset_sync gem):

> heroku run rake assets:precompile --app [app_name]

In rails4 by default assets gets the digest URL with them and getting served.

If you want you can use some middleware to redirect assets from non digest path to digest path.

or you can turn off the digest in production.rb file all together like below.

config.assets.digest = false

If you want that redirect solution I can post here as well.

Let me know!

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