3
votes

So in my app i have a card where i want to dynamically set the background image via ActiveStorage like so:

  <div class="card" style="background-image: url(<%= rails_blob_path(post.images.first) %>)">

 </div>

however, the image is not visible. Inside chrome i also get in the element.style property "invalid type property" as an error.

If i inspect the card element, the url is loaded like so:

`background-image: url(/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCdz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--9be6ec89650623cc4a22214c34635f2924f8feea/Frame%20(1).png)`

Taking the url and adding localhost:3000 to it loads the image:

localhost:3000/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCdz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--9be6ec89650623cc4a22214c34635f2924f8feea/Frame%20(1).png

Rendering the image normally inside an img tag works fine:

<%= image_tag(post.images.first) %>

Also, changingrails_blob_path to rails_blob_url makes no difference at all. The only change is that there is a localhost:3000 added to the url in rails_blob_url:

http://localhost:3000/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCdz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--9be6ec89650623cc4a22214c34635f2924f8feea/Frame%20(1).png

Adding a height/width to the card class results also in no difference.

Here is a reference i've found, seems like they are using the same approach as i do: Ruby on rails 5.2 - background image with active storage

Any ideas where the problem might be?

Thanks in advance everyone!

Greetings!

1
Try removing forward slash, have a look at stackoverflow.com/questions/22075730/…Nick Roz
Are you trying to make the image downloadable or just show it?hashrocket
No download required. The image needs to be set as an div background, like shown above. Rendering the image via image_tag works and getting the download url works also. This has something with CSS to do i guess and the way i inject the background-image url.Prometheus

1 Answers

5
votes

Thanks everyone for all of your input!

I was able to fix it. Just in case someone runs into the same issue:

Add single quotes to your path:

Solution:

 <div class="card" style="background-image: url('<%= rails_blob_url(post.images.first) %>'); height: 100px; background-position: center;">

For comparison (before):

 <div class="card" style="background-image: url(<%= rails_blob_path(post.images.first) %>)">

Double quotes don't work in this example.

This would be probably not even an issue if i just would have used the scss file instead of adding it directly to the div.

Cheers!