Forum: Ruby on Rails Displaying line breaks & paragraphs using 'simple_format' ?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Tom H. (Guest)
on 2009-02-25 01:40
Hi there,

I need to:

1. STORE a text of the below format in a (MySQL) database (using a
'textarea'), and then
2. RETRIEVE & DISPLAY it in exactly the same format (meaning: keeping
all paragraphs/line breaks).

The intended text format looks like this:

Blah blahblah blah blah blahblah blah blah
blahblah blah blah blahblah blah, blah
blahblah.          <- NEW PARAGRAPH

Blah blahblah blah blah.      <- LINE BREAK
Blah blahblah blah blah blahblah blah blah
blahblah blah blah blahblah blah, blah

Until now:
- the text is stored in exactly this format in a 'text' field in the
database (which I believe is the correct way to do it)
- I have used 'simple_format'
for displaying

The problem is: LINE BREAKS are displayed correctly, but NOT the
PARAGRAPHS (they appear like simple line breaks).

What am I doing wrong ?!

Thanks a bunch for any hints and help !
Gavin (Guest)
on 2009-02-25 19:50
(Received via mailing list)
Hey Tom-

sadly I noticed this same issue with simple_format

I get around it by adding a model method to whatever the class is with
the text.
For example, if I have pages, and each page has a body, I'll add a
method like so:

class Page
  def format_breaks
    body.gsub("\n", "<br />")

and then call @page.body.format_breaks in the view.

This might lead to performance issues if you have an awful lot of text
though so it might be more efficient to create an after_save callback

Something like:

class Page
  after_save :format_breaks
  def format_breaks
     update_attribute :body, body.gsub("\n", "<br />")

This will update the entry in the database after you save so all you
have to call in the view is <%= @page.body %>

Note - to keep your XHTML valid, you'll need to wrap the whole thing
in paragraph tags (I believe?)

  <%= @page.body %>

Hope that helps?
Tom H. (Guest)
on 2009-02-25 21:18
Thanks, Gavin! That definitely helps...
This topic is locked and can not be replied to.