Search code examples
ruby-on-railsrails-activestorage

Is there a way to set a background image within the CSS with Rails Active Storage?


I know it's possible to set a background image within the html.erb using the style attribute, like so:

<div style="background-image: url('<%= rails_blob_url(object.image) %>');">
    ...
</div>

But is it possible to call an image blob within the CSS and use that as a class on the div? It does seem unorganized to have a style attribute when there's a dedicated CSS file.


Solution

  • One way to achieve ActiveStorage URLs in the style.css file is to change file extension to style.css.erb and call helper like this

    background-image: url("<%= Rails.application.routes.url_helpers.url_for(object.image) %>") 
    

    I used helper like

    Rails.application.routes.url_helpers.url_for

    because view helper will no longer be available.

    But I believe it should only work with sprocket not on webpack since ERB interpolation only works in Sprockets. Webpacker does not pass assets through ERB.

    NOTE: We should never use ActiveStorage URL like this because asset compilation is done at deploy time in production, not for each request so the data will become stale and ActiveStorage is meant for CRUD.