Let’s say you have a model Post title:string body:text.

In the form you already have a field <%= form.text_area :body %> and you don’t need to change anything there.

The thing about markdown is just about parsing text and displaying it with the propper formatting.

To parse text into markdown you will need the gem redcarpet.

Also, here’s a good markdown cheatsheet

Gemfile

bundle add redcarpet

Basic implementation:

# application_helper.rb
def markdown(text)
  return '' if text.nil?

  extensions = %i[
    hard_wrap autolink no_intra_emphasis tables fenced_code_blocks
    disable_indented_code_blocks strikethrough lax_spacing space_after_headers
    quote footnotes highlight underline
    ]
    Markdown.new(text, *extensions).to_html.html_safe
end

More advanced implementation with render_options:

# application_helper.rb
def markdown(text)
  return '' if text.nil?

  render_options = { hard_wrap: true, link_attributes: { target: '_blank' } }
  extensions = { fenced_code_blocks: true, strikethrough: true, tables: true, autolink: true }
  renderer = Redcarpet::Render::HTML.new(render_options)
  Redcarpet::Markdown.new(renderer, extensions).render(text).html_safe
end

The options variable defines parsing settings that you use from Redcarpet.

Now in a view you can parse anything to markdown:

<%= markdown(@post.body) %>

Bonus - beautify your forms’ text input area: #

<%= form.text_area :content, 
  style: "width: 100%", 
  rows: 8, 
  maxlength: 5000, 
  placeholder: 'User Markdown for formatting' 
%>

Part 2: customize markdown code blocks with gem rouge