1

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?

jpw
  • 18,697
  • 25
  • 111
  • 187

2 Answers2

1

Rails on production mode will precompile assets so that all images on assets folder (and child folders) will be precompiled and saved as image name-fingeprint on public folder, for example: i have a image assets/images/bgs/pragmatic_programmer.jpg, then after run command rake assets:precompile, this image will become /public/assets/bgs/pragmatic_programmer-9aa8a13ac97f205fe891bee7c42c6e711f997186d8975d5a4106ca2fe53ccc61.jpg.

That the cause your app work on development mode but not on production mode since the images path changed, you can access new compiled images by ActionView::Helpers::AssetTagHelper#image_path as below

#application.html.haml
%style
  body::after {
  content: "";
  background: url(= image_path("bgs/abc.jpg"));
  ...
}

you could test on development mode, just run rake assets:precompile before start server.

Lam Phan
  • 3,405
  • 2
  • 9
  • 20
0

The answer is for the style definition to be:

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

that works on both development and production.

jpw
  • 18,697
  • 25
  • 111
  • 187