Preloading a text input area (text_area) with data that contains a line breakMarch 23rd, 2012 | Posted by in Ruby on Rails
I recently came across the problem of having to preload a form with data. The data that was to be shown by text_area_tag was multi-lined and contained a line break. Whatever i tried, the rendered text input area ignored my attempt to break the lines and escaped my line breaks. This lead to <br/> tags and \n in the rendered text box, but no line break.
Initially i though the \n linebreak stored in the database content was enough for the text_area to break the lines. But it turned out not to be (the \n was shown insinde the text area), so some googling revealed, that i should use .gsub(/\\n/, ‘<br/>’) to replace the new lines with line breaks. But as before no line break and the <br/> showed up within the content of the text area.
Finally i found a solution by using the <%raw … %> tag (http://api.rubyonrails.org/classes/ActionView/Helpers/OutputSafetyHelper.html#method-i-raw), which print the result as it is, without escaping the characters for HTML. So the final solution looked like this
<%=raw text_area_tag :keywords, keywords, :rows => 8 %>
And the result rendered like it should …