Search code examples
ruby-on-railsbackground-imageasset-pipelinewebpacker

Rails 6/webpacker... how get background images to work BOTH in development and on Heroku?


In a Rails 6 app, I have an image file in app/assets/images/bgs/abc.jpg

To attach that image to body background, how can I have a style declaration in a style tag in application.html.haml that works the same for both local development and when pushed to heroku?

Works in development, but not Heroku, due I suppose to asset handling differences:

#application.html.haml
%style
  body::after {
  content: "";
  background: url("/assets/bgs/abc.jpg");  ### WORKS DEVT ONLY ###
  background-size: cover;
  background-repeat: no-repeat;
  opacity: 0.12;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  background-attachment: fixed;
  z-index: -1;   
  }

I understand I should be using asset_path but none of these work in development:

background: asset_path("/bgs/abc.jpg");
background: asset_path("bgs/abc.jpg");
background: asset_url("/bgs/abc.jpg");
background: asset_url("bgs/abc.jpg");

There is a spectacular amount of inconsistent information out there, some cases saying use asset-url or asset-path, some cases saying asset_url or asset_path, and even some cases saying use url(~filename.jpg), some say use background: some say background-image.

Is there a simple way to use a background image with the exact same code working both on development and Heroku?


Solution

  • The answer is for the style definition to be:

    background: url( asset_path("bgs/abc.jpg") );

    that works on both development and production.