ruby-on-railshtml-injections

Rails 3 HTML Injection


Currently following the Learning Rails Screencasts at http://www.buildingwebapps.com/learningrails, making any necessary changes to work in Rails 3. However, in the tenth episode, I'm having a problem when rendering html code out of the database. The Page model in the tutorial has a body field, where the html of each page is put. The viewer controller's 'show' method grabs a Page from the database, and yields the contents of @page.body into the view. However, instead of rendering tags such as h1 properly, when I view the html source in the browser my tags are being rendered as <h1;@gt. Is there any way I can fix this?

Just for reference, my 'show' view is as follows:

<%= @page.body %>

Solution

  • Try this:

    <%= raw(@page.body) %>
    

    Raw method prevents escaping HTML characters.