SJU
SJU

Reputation: 3272

Rails image url in poduction

When I put my website in production using git push heroku master the url in my CSS does not refer to the right image url.

Here is my situation in development environment :

Here is my situation in production (when I "View Page source") :

For the others images called directly from app/views/* it's ok (<%= link_to image_tag("xxx.png") %>)

In config/environments/production.rb I have :

config.assets.precompile += ['style.css']
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
config.assets.digest = true
config.assets.compile = true
config.serve_static_assets = true

I'm following this great tutorial.

Upvotes: 1

Views: 820

Answers (2)

SJU
SJU

Reputation: 3272

I resolve my problem thanks to multiple answers found here and somewhere else (can't found where anymore sorry). Here is my solution to make things work without putting all my ressources into the public folder.

  1. I deleted all ressources from public/images & stylesheets & javascript
  2. I renamed my style.css to style.css.scss.erb
  3. I replace every background: url("../images/xxx.png"); to background: url(<%=asset_path "xxx.png"%>); from my CSS
  4. I executed this command before pushing into production : bundle exec rake assets:precompile RAILS_ENV=production

Thanks @RichPeck for your post which helps me to understand the process of assets pipelines

Upvotes: 1

Richard Peck
Richard Peck

Reputation: 76774

SCSS

The problem, from what I can see, is that you're not using any CSS preprocessors (SCSS / SASS), cancelling out the ability for the Rails helper asset-url.

I'd do this to start with:

#app/assets/stylesheets/style.css.scss
background: asset-url("logo.png");

Asset Pipeline

This will make sense if you look at how the asset pipeline works

Basically, the asset pipeline is a place to put all your css / image / javascript files, which your application can call, either statically or dynamically. Whilst in development, the asset_pipeline works very well to provide you with a central location for all your files -- all being called dynamically.

--

Production

The "problems" happen when most people want to use the asset pipeline in production. Production generally requires static assets, which means precompilation:

In the production environment Sprockets uses the fingerprinting scheme outlined above. By default Rails assumes assets have been precompiled and will be served as static assets by your web server.

Asset precompilation is when Rails will "compile" your CSS / Image / Javascript files into a series of "minified" versions - making them much more efficient to load

The problem with the precompilation process is actually loses all the "dynamic" aspects of the files, meaning if you want to include things like asset-url, you'll need to use a preprocessor to manage the dynamic aspects of these files.

Upvotes: 3

Related Questions