Rails: How to reference images in CSS within Rails 4

The hash is because the asset pipeline and server Optimize caching http://guides.rubyonrails.org/asset_pipeline.html

Try something like this:

 background-image: url(image_path('check.png'));

Goodluck


Don't know why, but only thing that worked for me was using asset_path instead of image_path, even though my images are under the assets/images/ directory:

Example:

app/assets/images/mypic.png

In Ruby:

asset_path('mypic.png')

In .scss:

url(asset-path('mypic.png'))

UPDATE:

Figured it out- turns out these asset helpers come from the sass-rails gem (which I had installed in my project).


In Rails 4, you can reference an image located in assets/images/ in your .SCSS files easily like this:

.some-div {
  background-image: url(image-path('pretty-background-image.jpg'));
}

When you launch the application in development mode (localhost:3000), you should see something like:

background-image: url("/assets/pretty-background-image.jpg");

In production mode, your assets will have the cache helper numbers:

background-image: url("/assets/pretty-background-image-8b313354987c309e3cd76eabdb376c1e.jpg");

Sprockets together with Sass has some nifty helpers you can use to get the job done. Sprockets will only process these helpers if your stylesheet file extensions are either .css.scss or .css.sass.


Image specific helper:

background-image: image-url("logo.png")

Agnostic helper:

background-image: asset-url("logo.png", image)
background-image: asset-url($asset, $asset-type)

Or if you want to embed the image data in the css file:

background-image: asset-data-url("logo.png")