Reputation: 2662
I'm building a blog in Rails and want to add images to posts.
I'm basically writing the HTML into a text area and save it into the database. Then I print the post content with @post.content
on my show page.
Normally, you can use <%= image_tag 'mypic.jpg %>
to render the dynamic image url, but since it gets saved as a string in the database, this doesn't work in this case.
How do I save my image tag in the database?
How do cms or blog engines and editors like CKeditor deal with this problem?
Upvotes: 0
Views: 813
Reputation: 9308
By default rails will escape the HTML tags in a string. To print the post content string in HTML format, you can use the raw()
method. You can also use html_safe
. Raw is usually preferred because it won't raise an exception if the value passed to it is nil.
<%= raw @post.content %>
or <%= @post.content.html_safe %>
Keep in mind, you should only use these methods on strings that you know are safe from cross-site scripting XXS. If your site is accepting user input, this could be a security vulnerability.
CKEditor works with file uploading gems like Carrierwave or Dragonfly. Implementing CKEditor with img uploads requires a new database table, which will save images on your server when uploaded through the text editor. The path to the image is saved within the Post string in an <img>
tag. CKEditor also generates a set of routes to handle paths for uploaded images.
Upvotes: 1