skip to content

File Uploads & Rich Text

Active Storage attaches uploaded files to models and keeps them on disk or a cloud service, and Action Text stores editor HTML with embedded images. Interviewers probe uploads, variants and delivery.

part ofRuby on Railsread it →
on this pageshow

explore

questions

18

In Rails 8.1, how do you add an Action Text rich-text field to a model, and where is its content stored?

level: juniorimportance: must knowfreq 52%

answer

  1. bin/rails action_text:install
  2. no column on the model's table
  3. action_text_rich_texts, polymorphic record
  4. form.rich_textarea renders trix-editor
  5. <%= @lesson.notes %> renders sanitized HTML

basics

~20 s

Run 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 lines
ruby
class 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

for a junior

Recall the install command, has_rich_text, form.rich_textarea and that <%= record.notes %> renders the content.

for a middle

Explain the action_text_rich_texts table, the generated association and methods, and why the field must still be permitted in the controller.

for a senior

Account for the separate table in queries, the touch on the parent for caching, and class renames that need record_type updates.

for a principal

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).

open as a page

In a Rails model, what does has_one_attached :avatar set up, and which tables hold the uploaded file's data?

level: juniorimportance: must knowfreq 72%

basics

~20 s

has_one_attached :avatar adds no column; it defines an avatar_attachment association to a polymorphic row in active_storage_attachments, which points at a row in active_storage_blobs describing the file. The bytes themselves live in the configured storage service.

open as a page

In a Rails 8.1 app, what does config/storage.yml declare, and how does each environment choose its Active Storage service?

level: juniorimportance: must knowfreq 60%

basics

~20 s

config/storage.yml names storage services, each with an adapter (Disk, S3, GCS or Mirror) and its settings. Each config/environments file sets config.active_storage.service to one of those names, and every blob records the service it was stored on.

open as a page

When a teacher drops an image into an Action Text Trix editor, how is the file uploaded, referenced in the HTML and rendered later?

level: middleimportance: must knowfreq 40%

basics

~20 s

Action Text's JavaScript direct-uploads the file to Active Storage when it is dropped, and the body stores an action-text-attachment tag with the blob's signed global id. Saving attaches the blob as an embed; rendering draws the blob partial.

open as a page

In Active Storage, how is a named variant such as :thumb on has_one_attached generated, stored and reused?

level: middleimportance: must knowfreq 56%

basics

~20 s

A named variant is declared in has_one_attached's block with attachable.variant. Active Storage transforms the original with image_processing on first use, stores the result as its own blob, and records it in active_storage_variant_records so later requests reuse it.

open as a page

In Rails, what URL does rails_blob_path or url_for give for an Active Storage file in redirect mode, and how long does it stay valid?

level: middleimportance: must knowfreq 52%

basics

~20 s

In redirect mode the helper returns a stable Rails URL containing the blob's signed_id. Requesting it makes Rails answer 302 with a signed service URL that expires after service_urls_expire_in (5 minutes); the Rails URL itself never expires unless urls_expire_in is set.

open as a page

Action Text stores the editor's HTML unsanitized; when is it sanitized, and which ways of outputting it skip that step?

level: middleimportance: should knowfreq 35%

basics

~20 s

Action Text keeps the submitted HTML as is and sanitizes it when rendering: <%= record.notes %> runs it through a safe-list sanitizer after rendering attachments. Outputting body.to_html or to_trix_html with raw or html_safe skips that, and to_plain_text is not HTML-safe.

open as a page

With Active Storage's direct_upload: true file field, how does the file reach the storage service, and what does the form submit to Rails?

level: middleimportance: should knowfreq 44%

basics

~20 s

Active Storage's JavaScript intercepts the submit, asks Rails to create a blob record, uploads the bytes straight to the storage service with the returned URL and headers, then submits the form with the blob's signed_id instead of the file.

open as a page

In Active Storage, how do purge, purge_later and detach differ, and what happens to the files when the owning record is destroyed?

level: middleimportance: should knowfreq 48%

basics

~20 s

detach deletes only the attachment row; purge deletes the attachment, the blob row and the stored file right away; purge_later deletes the attachment and enqueues ActiveStorage::PurgeJob for the rest. Destroying the owner purges later by default (dependent: :purge_later).

open as a page

Active Storage in Rails 8.1 has no attachment validators; how would you reject an avatar over 5 MB or a non-PDF contract?

level: middleimportance: should knowfreq 50%

basics

~20 s

Write a custom validate method that checks attachment.attached?, blob.byte_size and content_type and adds errors. The content type is sniffed from the bytes when the file is attached, and direct-uploaded files are already stored, so rejected ones need cleanup.

open as a page

When should Active Storage serve files in proxy mode instead of redirect mode, and what does the proxy controller do differently?

level: middleimportance: should knowfreq 38%

basics

~20 s

In proxy mode the Rails app streams each file from storage to the browser under your own domain, with public cache-forever headers. Use it for a CDN in front of files; it costs app-server time per download.

open as a page

What changes when an Active Storage service in config/storage.yml is marked public: true?

level: middleimportance: should knowfreq 30%

basics

~20 s

With public: true, blob.url returns the object's permanent, unsigned URL instead of a short-lived signed one, and S3 uploads are written with a public-read ACL. The bucket must allow public reads, and every file on that service becomes readable by anyone with its address.

open as a page

A Rails page listing thirty lessons with their Action Text notes fires a query per row; what do with_rich_text_notes, its _and_embeds variant and with_all_rich_text preload, and what do they not?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Each rich-text attribute is a has_one association, so a list loads one row per lesson. with_rich_text_notes preloads those rows, with_rich_text_notes_and_embeds also their embed attachments and blobs, and with_all_rich_text every rich-text attribute. Rendering embeds still looks each one up.

open as a page

A Rails page listing fifty freelancers with avatar thumbnails runs hundreds of queries; how do with_attached_avatar and with_all_variant_records fix Active Storage's N+1?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Each avatar lazily loads its attachment row, its blob and, for processed variants, its variant record and that record's blob. Freelancer.with_attached_avatar preloads all of them in a fixed number of queries; with_all_variant_records does the same for one record's attachments.

open as a page

A Rails app keeps private property-inspection photos in Active Storage; how would you put a CDN in front of them without exposing them to anyone holding a link?

level: seniorimportance: should knowfreq 30%

basics

~20 s

The built-in CDN recipe (proxy routes on a CDN host) caches files publicly for anyone holding a URL. For private photos, expire signed ids at some cost to hit rate, or disable the default routes and serve through an authorizing controller.

open as a page

How do you embed a non-file record, such as a repertoire Piece, inside Action Text content with ActionText::Attachable?

level: middleimportance: nice to knowfreq 20%

basics

~10 s

Include ActionText::Attachable in the model and insert an action-text-attachment tag carrying the record's attachable_sgid. When the content renders, Action Text resolves the sgid to the current record and renders its partial inside the tag.

open as a page

What do has_rich_text's encrypted: true and store_if_blank: false options change about how Action Text stores a lesson's notes?

level: middleimportance: nice to knowfreq 18%

basics

~20 s

encrypted: true makes the attribute use ActionText::EncryptedRichText, which encrypts the body column with Active Record encryption (non-deterministic). store_if_blank: false stops a blank value from creating a rich-text row and marks an existing one for destruction.

open as a page

How do you use Active Storage's Mirror service to move a live Rails app's files from one storage service to another?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

Define a Mirror service whose primary is the current store and whose mirrors include the new one, make it the active service, backfill existing blobs with mirror_later, verify the copies, then switch to the new service.

open as a page