Search code examples
ruby-on-railsredcloth

How does one add RedCloth to a form_for?


An embaressing question, but I can't seem to translate the documentation to an actual form_for. This is all the site provides..

RedCloth.new("Some text").to_html
 #=> "<p>Some text</p>"

I get that that's how I parse it after its been saved. But how do I save it as marked up text?

Here's my attempt at beginning this, but I don't know how to set the parameter to save the textarea as RedCloth. Any ideas?

- form_for @text do |f|
   # some RedCloth instantiation
   f.submit

Solution

  • You don't save the parameter parsed as RedCloth like that, nor would I recommend it. Parsing it into RedCloth will result in the original value being lost unless you stored the output in an alternate field, which is what I would recommend.

    You can use a before_save in your model to parse that value and store it:

    before_save :parse_text
    
    # your model methods go here
    
    private
    
      def parse_text
        self.parsed_text = RedCloth.new(text).to_html
      end
    

    When you want to render the parsed_text value in your view you'll have to tell Rails that it's safe by doing this:

    @object.parsed_text.html_safe
    

    However, the code contained here does not account for people mixing Markdown and HTML, so be very careful how you use it.