I personally had the opportunity to introduce ʻAction Text
, so make a note.
When developing something like a blog service, I was wondering how to introduce ʻActionText into the ʻArticle` model, so I hope it helps someone.
What is Action Text?
One of the features that has been available since rails6.
Introduce rich text content and editing capabilities to Rails.
What I want to do this time
I would like to create an article posting service.
Create an Article model with three data, title, description, and body, and introduce ActionText to edit the body.
ʻCreating a model that introduces ActionText`
ʻGenerates an Article
is the title of the article and description` is the description of the article. Note that we do not create columns to store the body data.
rails g model Article title:string description:text
ʻActionText` can be installed with the following command.
When you install ActionText, two migration files are generated.
One is a file related to ʻActive Storage
, and the other is a file that creates a table of ʻActionText.
The latter table is the key to the data structure we want to discuss in this article.
Rich text content is stored in its own RichText model, which is associated with any existing Active Record model in your application. All embedded images (and other attachments) are automatically stored in Active Storage and associated with the included RichText model.
class CreateActionTextTables < ActiveRecord::Migration[5.2] def change create_table :action_text_rich_texts do |t| t.string :name, null: false t.text :body, limit: 16777215 t.references :record, null: false, polymorphic: true, index: false t.datetime :created_at, null: false t.datetime :updated_at, null: false t.index [ :record_type, :record_id, :name ], name: "index_action_text_rich_texts_uniqueness", unique: true end end end
By associating the above data with the ʻArticle` model, it is possible to edit the content of the article with rich text.
Linking the data is easy, add it to the model as follows.
class Article < ApplicationRecord has_rich_text :content end
What kind of data structure is it?
As explained above, the ʻArticle
table holds title
, and the content of the article (content
) is kept in the table ʻActionText :: RichText. If you look at the results of the console below, it will be easier to imagine.
#Get Article model data irb(main):001:0> Article.all.first => #<Article id: 1, created_at: "2020-07-11 13:19:00", updated_at: "2020-07-11 13:19:00", title: "test", description: "testです"> #ActionText associated with the Article model::Get RichText data irb(main):002:0> Article.all.first.content => #<ActionText::RichText id: 1, name: "content", body: #<ActionText::Content "<div class=\"trix-conte...">, record_type: "Article", record_id: 1, created_at: "2020-07-11 13:19:00", updated_at: "2020-07-11 13:19:00"> #How to get the content of an article? irb(main):003:0> Article.all.first.content.body => #<ActionText::Content "<div class=\"trix-conte...">