0

I'm trying to gather some information from a database, Currently a user fills out a form and the textbox fills in html format accordingly.

The issue is when its passed to the database its saved down as this

<p>How would this work?</p><p><br/></p><p>I need to know, IF the HTML formatting is here</p><p><br/></p><h1>unfortunatly it may stick</h1><h4>Although it might not,</h4><p>Only time will tell, If the <b>Font </b><i>Stays </i><u>or </u><strike>not</strike></p>

The issue i have is when i call it do be placed back into the page it displays as the same, Rather than keeping the format.

I'm using Rails to call the DB so heres my little code to call the DB

<% @events.each do |ev| %>
<%= ev.details %>
<% end %>
ddsbro
  • 217
  • 2
  • 12

2 Answers2

2

html_safe

Rails by default escapes all the text to prevent any injecting and such type of attacks, if you know that the data is safe then tell rails that it is, just add html_safe to the string

<% @events.each do |ev| %>
  <%= ev.details.html_safe %>
<% end %>

raw

Note that #html_safe is a String helper, so it works on String objects, if for any reason this string could be a nil object, then it would raise an error undefined method html_safe for nil

In that case using raw might be safer, because it would return an empty string for nil instead of raising an error.

Internally raw calls #to_s then mark it the result string as html_safe, in the nil case it will convert nil to an empty string, then mark it as safe.

<% @events.each do |ev| %>
  <%= raw ev.details %>
<% end %>

sanitize

You might also want to consider using sanitize which allows only a certain set of tags and cleans the rest, this is a nice combination between allowing html rendering and preventing evil tags, you can read about the sanitize helper here

Sanitizing a nil object returns nil, I would say it's safe because the puts will call #to_s on the nil object, which would convert nil to an empty string.

<% @events.each do |ev| %>
  <%= sanitize ev.details %>
<% end %>
Mohammad AbuShady
  • 40,884
  • 11
  • 78
  • 89
  • and i almost didn't give you the answer award, Well done good sir, Exactly what i needed and helps others :) – ddsbro Sep 03 '15 at 11:10
1

Use raw method Reference

<% @events.each do |ev| %>
  <%= raw(ev.details) %>
<% end %>
Prashant4224
  • 1,551
  • 1
  • 14
  • 21