0

I am in the middle of implementing a text editor in my Rails app. My text editor only outputs html. When I'm saving it to my database, I need to stringify it. And when I load the text from my database it needs to parse stringified html to normal html.

1) parse html -> stringified html
2) parse stringified html -> html

How can I do this in Rails app?

JoHksi
  • 517
  • 1
  • 7
  • 26

1 Answers1

2

I recommend using a text type to store your html. Assuming you're storing it in a column called content, I would display it as such:

#controller
def show
  @model = Model.find(params[:id])
end

#view
<%= @model.content.html_safe %>

This will render content as HTML instead of printing tags.

Okomikeruko
  • 1,123
  • 10
  • 22
  • When I save the HTML, it seems like i need to save HTML as TEXT type. How is it different than STRING type? – JoHksi Jul 12 '16 at 20:37
  • Most databases limit `string` character maximums to 255, but a `text` can have up to 4,294,967,296 characters. See more: http://stackoverflow.com/questions/3354330/difference-between-string-and-text-in-rails – Okomikeruko Jul 12 '16 at 20:39
  • when I save HTML to database, should I still save it as String format: "

    sample

    " ? I tried without quotation mark and it's not working. And even if I put html output in quotation mark, it gives me an error on bracket.
    – JoHksi Jul 12 '16 at 20:55
  • Yes, still use quotations. Rails String variables are different than a database string datatype. When using `text` datatype, we mean when you generated the database model you would use `$ rails generate model ModelName content:text` as a part of your command line model generation. – Okomikeruko Jul 12 '16 at 21:01
  • That's exactly I did. When I try to save html in quotation mark under TEXT type, it gives me an error on brackets (like <>) saying `syntax error, unexpected tINTEGER, expecting end-of-input` – JoHksi Jul 12 '16 at 21:03
  • What error do you get without quotation marks? – Okomikeruko Jul 12 '16 at 21:17
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/117144/discussion-between-okomikeruko-and-johksi). – Okomikeruko Jul 12 '16 at 21:27
  • Hello, quick question. how did you get html code from the editor when you are using Froala? I am having hard time with it. Did you get it from the uI (editor) itself or did you call an API method? – JoHksi Jul 13 '16 at 00:28
  • According to the Froala API, I added the gem to the Gemfile, ran `bundle install`, added a CSS id to a form text_area_tag, then on page load ran some jQuery `$('textarea#wysiwyg').froalaEditor();` It automatically converts the output to HTML. – Okomikeruko Jul 13 '16 at 01:10