Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails images and assets not being loaded properly

For example, in my Rails application I have something like:

.wax_seal {
  background: url("wax-seal-small.png");
  display: block;
  height: 100px;
  margin: 0 auto;
  width: 92px;
}

.wax_seal:active {
  background: url('wax-seal-small-broken.png');
}

And in my config/environments/production.rb file:

# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = true

I manually invoke the compiling of assets:

bundle exec rake assets:precompile

And the files are created with hashes at the end of the name:

wax-seal-small-Uuhqwduhqwdoi234983jewf.png

So this doesn't work:

background: url("wax-seal-small.png");

But this works fine (when I manually type it in Chrome):

background: url("wax-seal-small-Uuhqwduhqwdoi234983jewf.png");

What step am I missing here? How can I make my CSS rules add in that little hash?

Adding config.assets.compile = true in config/environments/production.rb makes it work, but I read in the Rails guide that it's a bad practice due to significant performance hits.

like image 992
sergserg Avatar asked Jun 01 '13 21:06

sergserg


2 Answers

I found this in edgerails documentation: http://edgeguides.rubyonrails.org/asset_pipeline.html#css-and-sass

2.3.2 CSS and Sass

When using the asset pipeline, paths to assets must be re-written and sass-rails provides -url and -path helpers (hyphenated in Sass, underscored in Ruby) for the following asset classes: image, font, video, audio, JavaScript and stylesheet.

  • image-url("rails.png") becomes url(/assets/rails.png)
  • image-path("rails.png") becomes "/assets/rails.png"

The more generic form can also be used but the asset path and class must both be specified:

  • asset-url("rails.png", image) becomes url(/assets/rails.png)
  • asset-path("rails.png", image) becomes "/assets/rails.png"
like image 104
Zoltan Avatar answered Nov 02 '22 07:11

Zoltan


If you're using sass or less you can use background: image-url("wax-seal-small.png");

That will prepend the path to your file and append the cache buster hash.

Otherwise just reference it to the /assets directory. E.g. background: url("/assets/wax-seal-small.png");

like image 25
Marc Greenstock Avatar answered Nov 02 '22 08:11

Marc Greenstock