DR_ DR_ - 1 year ago 146
CSS Question

SASS: Background image url and rails controller variables

I need to show the profile picture of a user with the background-image property in a div class. The problem is, that the image-url and the asset-url are possible to call only from a scss file, and from a scss file, the @user variable is not visible. It says "undefined local variable or method `params'" when I try to access the user id. Couldn't find the answer in other topics.

background-image: image-url(<%= @user.avatar %>)


Your asset files are designed to be static in nature, especially when they've come down the asset pipeline with, precompiling, fingerprinting, and all. You can't have them change every time a different user logs in, because that would require a whole new precompiled, fingerprinted, and static asset.

Precompiling isn't a problem for you now because you're in the development environment, but will be an issue on production.

This is one of the rare scenarios where a style attribute is much more appropriate! Or, some in-page Javascript that would change the style attribute of all the elements that match your div's class/id/selector. You can utilize asset_url and/or image_url for this:

<img src="placeholder.gif" style="background-image: url(<%= asset_url(...)%>);" />

See the AssetUrlHelper documentation, which is available on any Rails view!