Ask A Question

Notifications

You’re not receiving notifications from this thread.

Setting background image from User uploaded asset

Gerard Donnelly asked in CSS

Hi,

I am trying to set a user uploaded image as the background for their profile but cant seem to get it working. I'm stuck on what way to reference the image in the background css style. I'm using Rails 6.

style="background url('<%= image_tag(@creator.profile_image) %>')"

style="background url('<%= @creator.header_image %>')"

Any help would be greatly appriciated.

Thanks,

Gerard

Reply

Assuming you're using ActiveStorage?

Should be like:

style="background: url('<%= image_url @creator.header_image %>');"
Reply

Hi Chris,

Weird. I tried your solution but still no luck. See image. I am using active storage. See image of error. "The asset "" is not present in the asset pipeline."

[img]https://i.imgur.com/7fpogii.png[/img]

If I just add it to a div on the page to test, it will show up.

<%= image_tag(@creator.header_image, style: 'width:100%') %>
Reply

Well, it looks like you don't have an image attached. That will obviously only work if there is an image attached. 🧐

Reply

Hi Chris,

Thanks for taking the time to help me. The funny thing is there is an image attached. If I just add the image tag on the page it loads fine:

<%= image_tag(@creator.header_image, style: 'width:100%') %>
Reply

Hmm, I wonder why then the string was "" then. I assumed that's what it would do when there was no attachment.

Try just printing out the image_url on the page directly. Once you figure out what's missing there, then you can add it to the style attribute.

You can always throw a byebug onto the page so you can fiddle with it while it's rendering.

Reply

Hi Chris,

Thanks for your help on this. I eventually got it solved. The following worked:

style="background-image: url(<%= rails_blob_url(@creator.header_image) %>)"

Thanks,

Gerard

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,563+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.