In Rails 8.1, how do you add an Action Text rich-text field to a model, and where is its content stored?
answer
- bin/rails action_text:install
- no column on the model's table
- action_text_rich_texts, polymorphic record
- form.rich_textarea renders trix-editor
- <%= @lesson.notes %> renders sanitized HTML
basics
~20 sRun bin/rails action_text:install and migrate, declare has_rich_text :notes on the model, and use form.rich_textarea :notes in the form. The HTML is stored in a row of action_text_rich_texts linked polymorphically to the record, not in the model's table.
solid answer
~40 s`bin/rails action_text:install` pins `trix` and `@rails/actiontext` (or adds the npm packages), copies the content and blob partials and `actiontext.css`, and installs migrations for `action_text_rich_texts` plus the Active Storage tables; then `bin/rails db:migrate`. In the model, `has_rich_text :notes` adds no column: it defines `has_one :rich_text_notes`, an `ActionText::RichText` row whose polymorphic `record_type`/`record_id` and `name` ("notes") point back at the lesson and whose `body` holds the HTML; it autosaves, is destroyed with the record and touches it on change. In the form, `form.rich_textarea :notes` renders a `<trix-editor>` bound to a hidden input; permit `:notes` like any attribute. In a view `<%= @lesson.notes %>` renders the body sanitized inside a `trix-content` layout, and `notes.to_plain_text` gives text for excerpts. In 8.1 `rich_textarea` is the primary helper name (`rich_text_area` is an alias), and Trix comes from the `action_text-trix` gem.
code
ruby · 9 linesclass Lesson < ApplicationRecord
belongs_to :student
has_rich_text :notes
end
lesson = Lesson.create!(student: ana, notes: "<h1>Scales</h1><p>C major, two octaves</p>")
lesson.notes? # => true
lesson.notes.to_plain_text # => "Scales\n\nC major, two octaves"
lesson.rich_text_notes # => #<ActionText::RichText name: "notes", record_type: "Lesson", ...>go deeper
Recall the install command, has_rich_text, form.rich_textarea and that <%= record.notes %> renders the content.
Explain the action_text_rich_texts table, the generated association and methods, and why the field must still be permitted in the controller.
Account for the separate table in queries, the touch on the parent for caching, and class renames that need record_type updates.
Decide whether rich text belongs in Action Text's shared table or in a dedicated column or document store, weighing editing features against querying and reporting.
## Installing Action Text **Action Text** adds rich-text editing to Rails: a WYSIWYG editor in the browser (**Trix**), a model for the content, and rendering helpers. In a music-teacher app, a lesson's notes are a good fit: headings, lists, links and embedded images of sheet music. ```bash bin/rails action_text:install bin/rails db:migrate ``` The installer: - pins `trix` and `@rails/actiontext` (to `actiontext.esm.js`) in `config/importmap.rb`, or adds the npm packages when the app uses a JavaScript bundler, and imports both in `app/javascript/application.js`; - creates `app/assets/stylesheets/actiontext.css` with the Trix styles; - copies `app/views/layouts/action_text/contents/_content.html.erb` and `app/views/active_storage/blobs/_blob.html.erb`, the two partials you customize for rendering; - installs migrations for `action_text_rich_texts` and the Active Storage tables, because embedded files are stored with Active Storage. In Rails 8.1 the Trix assets come from a separate gem, `action_text-trix` (pinned `~> 2.1.15`, so Trix 2.1 at 2.1.15 or a later 2.1 patch), which `actiontext` depends on, so Trix can be updated without a Rails release. ## Declaring the field ```ruby class Lesson < ApplicationRecord has_rich_text :notes end ``` **`has_rich_text`** adds nothing to the `lessons` table. It generates: - `has_one :rich_text_notes`, an `ActionText::RichText` scoped to `name: "notes"`, with `autosave: true` and `dependent: :destroy`; - a reader `notes` that returns the existing rich text or builds a new one, a predicate `notes?`, and a writer `notes=` that assigns the body; - scopes `with_rich_text_notes` and `with_rich_text_notes_and_embeds` for preloading. ## The table | Column | Purpose | |---|---| | `name` | which rich-text attribute (`notes`) | | `body` | the HTML, a long text column, serialized through `ActionText::Content` | | `record_type`, `record_id` | polymorphic link to the owning record | | `created_at`, `updated_at` | timestamps | A unique index on `record_type, record_id, name` allows one row per attribute per record. Because `record_type` stores the class name, renaming `Lesson` means updating those rows. `ActionText::RichText` `belongs_to :record, touch: true`, so editing the notes bumps the lesson's `updated_at`, which keeps cache keys correct. It also `has_many_attached :embeds` for files in the content. ## The form and the controller ```erb <%= form_with model: @lesson do |form| %> <%= form.text_field :title %> <%= form.rich_textarea :notes %> <%= form.submit %> <% end %> ``` `form.rich_textarea` renders a hidden input holding the current HTML (`to_trix_html`) and a `<trix-editor>` element linked to it, with `data-direct-upload-url` and `data-blob-url-template` attributes so pasted images can upload. `rich_textarea` is the primary name in Rails 8.1 and `rich_text_area` remains as an alias; since 8.1 the helper can also take a block whose rendered HTML becomes the initial content. In the controller the field is an ordinary string attribute: `params.expect(lesson: [:title, :notes])`. ## Reading and rendering 1. `<%= @lesson.notes %>` calls `to_s`, which renders the body through the `action_text/contents/content` partial inside the copied layout (a `div.trix-content`), resolving embedded attachments and **sanitizing** the result. 2. `@lesson.notes.to_plain_text` strips markup for excerpts, search indexing or emails; it is **not** HTML-safe and must not be marked safe. 3. `@lesson.notes.body` is the `ActionText::Content` object; `notes.blank?` and `present?` are decided from the plain text. 4. `Lesson.create!(notes: "<h1>Scales</h1><p>C major, two octaves</p>")` works from code, seeds or tests, since the writer accepts HTML. ## Things that trip people up - Forgetting to permit `:notes` makes the editor appear to work while nothing is saved. - `Lesson.where(notes: ...)` does not work: the content lives in another table, so queries need a join on `rich_text_notes`. - Images inside the editor need Active Storage configured, including `libvips` for the image previews the blob partial renders.
- Why can you not filter lessons with where(notes: ...)?`has_rich_text` adds no `notes` column; the HTML lives in `action_text_rich_texts.body`. A query has to join the generated association, for example `Lesson.joins(:rich_text_notes).where("action_text_rich_texts.body LIKE ?", "%arpeggio%")`, and that search sees raw HTML, including markup and attachment tags.
- What happens to the notes row when a lesson is destroyed?The generated `has_one :rich_text_notes` is `dependent: :destroy`, so the `ActionText::RichText` row is destroyed with the lesson. Its `has_many_attached :embeds` then removes the embed attachments, and with the default `dependent: :purge_later` the embedded files are purged in the background.
- has_rich_text needs a text column named notes added to the lessons table
- Trix stores rich text as Markdown in the database
- In Rails 8.1 rich_text_area is the primary helper and rich_textarea does not exist
- to_plain_text returns HTML-safe text that can be output with raw
- Action Text needs no Active Storage tables unless you call has_one_attached
Assumes Rails 8.1: rich_textarea is the primary helper name with rich_text_area as an alias, the helper accepts a block for initial content, and Trix ships through the action_text-trix gem (~> 2.1.15).