I am really new to this, so please excuse me if this is a dumb question. I am saving some data using ruby on rails and one of those fields is a background for the divs I am rendering back on load. I created the partial layouts successfully but I have no clue how to embed the background into the div using the ruby variable.

So this is what I would do in jQuery
<div id="bubble" class="bubble" style="background:' + icon + '"></div>

My ruby field is <% event.icon %> ... how do I add it to this div ?


Thank you so much !

Dani AI

Generated

As discovered, the view needs to emit the Ruby value into the HTML so the browser can use it. answered the basic idea, but there are a few practical points that often get missed and will save time debugging.

If event.icon is an image filename managed by Rails, prefer generating a proper asset URL so fingerprinting and the asset pipeline are handled. For example, build a background-image with the asset helper instead of trying to paste a raw path. This avoids broken links when assets are precompiled or fingerprinted; see the Asset Pipeline guide.

<!-- inline background-image using the asset helper -->
<div class="bubble" style="background-image: url('<%= asset_path(event.icon) %>')"></div>

For server-side generation you can also use content_tag (keeps Ruby in Ruby, HTML in HTML) or, better yet, avoid inline styles entirely by using a CSS class per icon and defining the background in a stylesheet. That makes caching and maintenance easier and keeps HTML cleaner.

# example using content_tag in a helper or view
<%= content_tag :div, nil, class: "bubble", style: "background-image: url('#{asset_path(event.icon)}')" %>

Security and troubleshooting: never trust raw user input for CSS or URLs. Sanitize or whitelist allowed icon names/paths to prevent XSS. If the value is a color (like #fff) treat it differently than an image URL. If output doesn't appear, confirm the file is an ERB view (.html.erb), inspect the generated HTML in the browser, and check the asset URL in the network tab. For XSS guidance see Rails security docs on output escaping and XSS: https://guides.rubyonrails.org/security.html#cross-site-scripting-xss.

Hi,

Assuming your html file has an .rhtml, .erb or basically an extension that will ensure it is run through the ruby parser, then you can do this:

<div id="bubble" class="bubble" style="background: <%= event.icon %>">

</div>

R.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.