Search code examples
ruby-on-railsimageruby-on-rails-4asset-pipelinestylesheet

How to refer to rails assets from stylesheets?


I have a background image:

app/assets/images/bg.jpg

It works ok in development with the stylesheet as:

body {
 background: #111 url('bg.jpg') repeat-x; 
  color: #DDD;
  font: normal 90% "Trebuchet MS",Verdana,sans-serif;
  margin-left: 1.2em;
}

But in production it doesn't show and the logs show:

ActionController::RoutingError (No route matches [GET] "/assets/bg.jpg"):

When I am using html and js templates I can add .erb to add the rails pre-processing that will let me use things like paths and helpers, e.g. images_url

How can I either:

a) Do a similar thing with my stylesheet

b) Use a path that works in both dev and prod. I tried [nothing] and images/ and they didn't work.


Solution

  • The fix that worked for me was to have

     background: #111 url('<%= image_path "bg.jpg" %>') repeat-x;
    

    and name my file .erb as in default.scss.css.erb

    The other approaches didn't work.