Rails 4 - Background Image Appears in Localhost but not in production Rails 4 - Background Image Appears in Localhost but not in production ruby-on-rails ruby-on-rails

Rails 4 - Background Image Appears in Localhost but not in production


Your problem with almost certainly be to do with rake assets:precompile & your production environment

A good test will be to Right-Click > View Source on your production app and click on the CSS file where your background image is called. If your problem is your CSS is calling url("background-image.png") & when you click onto the file, it doesn't show, the solution is to use SCSS to precompile the assets dynamically


Precompiling The Assets With SCSS

We had the problem where you couldn't access the image files in the CSS, and found it was because the CSS was only referencing static url() locations; and in precompile, our app was calling images "backgroun-image-234234nsdfasfdjasdfk2jij234ij32i.png"

The way to fix that is to use SCSS to create dynamic links to the assets; allowing your app to put the correct path to the images, etc. Here is some live code:

#application.css.scss (yes, you need to rename it)@import 'layout/body'#app/assets/stylesheets/layout/body.css.scssbody {    background: asset_url('background-image.png')}

If you do this, and then when you push to production, you perform these commands, it should work:

rake assets:precompile RAILS_ENV=production


Fwiw, I just changed the name of the css file that referenced the background image from styleblah.css to styleblah.css.scss then changed background: url('/assets/images/imagetitle.png'); to background: asset_url('imagetitle.png'); and it worked perfectly.

Like the man says, run something along these lines: rake assets:precompile RAILS_ENV=production

then restart your web/http server (in my case unicorn) for good measure: sudo service unicorn restart