Rails 3: How to display properly text from "textarea"?

Misha Moroshko picture Misha Moroshko · May 2, 2011 · Viewed 27.9k times · Source

In my Rails 3 application I use textarea to let users to write a new message in a forum.

However, when the message is displayed, all newlines look like spaces (there is no <br />). Maybe there are other mismatch examples, I don't know yet.

I wonder what is the most appropriate way to deal with this.

I guess that the text that is stored in the database is OK (I see for example that < is converted to &lt;), so the main problem is the presentation.

Are there build-in helper methods in Rails for this ?

(simple_format does something that looks similar to what I need, but it adds <p> tags which I don't want to appear.)

Answer

Michael Koper picture Michael Koper · May 2, 2011

Rails got a helper method out of the box, so you dont have to write your own method.

From the documentation:

simple_format(text, html_options={}, options={})

my_text = "Here is some basic text...\n...with a line break."

simple_format(my_text)
# => "<p>Here is some basic text...\n<br />...with a line break.</p>"

more_text = "We want to put a paragraph...\n\n...right there."

simple_format(more_text)
# => "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>"

simple_format("Look ma! A class!", :class => 'description')
# => "<p class='description'>Look ma! A class!</p>"