In many projects we have the requirement to have a rich text editor available, for full documents, user profiles, blog posts, comments, product descriptions, …
And every time we think, which editor to use, some times we just get our current favorite, or the one we used in the last project, in my case those would be TineMCE and Quill respectively, but now w have a new “standard” for rails, since Rails 6 comes with ActionText bundled, so I decided to give it a try and wrote this quick blog post about it.
First we’ll install rails 6 (in the moment I’m writing this the latest version is 6.0.0.rc1), then we’ll just create a new rails app and do some scaffolding, after that I’ll review the code here and comment about the text editor.
rails new atsample cd atsample rails g scaffold post headline:string body:text rails db:migrate
Now if we just run our app, and access http://localhost:3000/posts we’ll see the same old textarea, to use ActionText we’ll need to tell rails we want it with these steps:
The previous command will add the yarn package and create two new migrations that we need to run, one to create the activestorage tables to allow image uploads and things like that, and the other to be used by ActionText itself.
Now lets add support for rich text on our post model, because pretty blog posts are always better 😀
After we executed the two migrations, lets change the Post model like the content bellow
class Post < ApplicationRecord has_rich_text :body end
That “has_rich_text” will make our body accept the rich content from ActiveText, then we need to change the form, since we are using the ugly scaffold template, we need to edit the file app/views/posts/_form.html.erb and change the body editor to “righ_text_area” like bellow:
<div class="field"> <%= form.label :body %> <%= form.rich_text_area :body %> </div>
And that will save the rich text into our body field.
One cool and perhaps useful thing on ActiveText is that you do not actually need a field in your model, you can for example, change the post to the following:
class Post < ApplicationRecord has_rich_text :body has_rich_text :content end
Then you add the “:content” field to the permit section in the posts controller and add the new “content” field in the form, exactly like the body field above, and ActionText will work flawlessly, but this time saving the content into ActionText table instead of using your model’s table.
This might be useful sometimes, but I think most of the times I’ll be using it in the model’s table anyway.
ActiveText is really flexible, and I’ll probably write another post later on how to configure it, add/remove buttons, …
So if you have any questions on ActiveText please leave a comment here and I’ll get back to you directly or in the next post.