skip to content

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%

answer

  1. one has_one per rich-text attribute
  2. with_rich_text_notes = includes
  3. _and_embeds adds embeds_attachments: :blob
  4. with_all_rich_text for every attribute
  5. rendering resolves each sgid separately

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.

solid answer

~40 s

`lesson.notes` reads the `rich_text_notes` association, so thirty lessons mean thirty extra queries. `has_rich_text :notes` defines `with_rich_text_notes`, which is `includes(:rich_text_notes)`, and `with_rich_text_notes_and_embeds`, which is `includes(rich_text_notes: { embeds_attachments: :blob })`; `Lesson.with_all_rich_text` includes every `rich_text_*` association the model has. The embeds preload helps code that reads `notes.embeds`, for example a thumbnail of the first image. Rendering the body is different: each `<action-text-attachment>` is resolved by its sgid through GlobalID, a lookup per embed that the preload does not replace. For an index page, show `to_plain_text` excerpts or cache rendered notes, and keep full rendering for the show page. `has_rich_text :notes, strict_loading: true` (default from `strict_loading_by_default`) makes a missed preload raise.

code

ruby · 18 lines
ruby
class Lesson < ApplicationRecord
  has_rich_text :notes, strict_loading: true
  has_rich_text :homework
end

class LessonsController < ApplicationController
  def index
    @lessons = Current.teacher.lessons.order(starts_at: :desc).with_rich_text_notes
  end

  def gallery
    @lessons = Current.teacher.lessons.with_rich_text_notes_and_embeds
  end

  def show
    @lesson = Current.teacher.lessons.with_all_rich_text.find(params.expect(:id))
  end
end

go deeper

for a junior

Recall that rich text lives in another table and that Model.with_rich_text_notes preloads it for a list.

for a middle

Explain the three scopes and what each includes, and why to_plain_text excerpts suit list pages.

for a senior

Diagnose the remaining queries from sgid resolution during rendering, and choose between excerpts, caching via touch and detail-only rendering; guard with strict_loading.

for a principal

Set conventions for where rich text is fully rendered and how list pages stay within a query budget as content grows.

## Where the queries come from `has_rich_text :notes` is a `has_one :rich_text_notes` association to `ActionText::RichText`. On an index page: ```erb <% @lessons.each do |lesson| %> <h3><%= lesson.title %></h3> <p><%= truncate(lesson.notes.to_plain_text, length: 160) %></p> <% end %> ``` each `lesson.notes` loads that lesson's rich-text row: one query for the lessons plus one per lesson. If the view also touches `lesson.notes.embeds`, each row adds queries for the embed attachments and their blobs. If it renders the full body with `<%= lesson.notes %>`, every embedded image or attachable is resolved as well. ## The generated scopes | Scope | Expands to | Use when | |---|---|---| | `Lesson.with_rich_text_notes` | `includes(:rich_text_notes)` | you read the body or plain text | | `Lesson.with_rich_text_notes_and_embeds` | `includes(rich_text_notes: { embeds_attachments: :blob })` | you also read `notes.embeds`, for thumbnails or counts | | `Lesson.with_all_rich_text` | `includes` of every `rich_text_*` association | the model has several rich-text attributes and the view uses them all | ```ruby @lessons = Current.teacher.lessons.order(starts_at: :desc).with_rich_text_notes ``` The scopes are ordinary `includes`, so Active Record loads each level with one query for all rows; how `includes` decides between separate queries and a join is the eager-loading topic's. ## What the embeds preload does not cover Rendering content does not walk the `embeds` association. `ActionText::Content` finds each `<action-text-attachment>` node and calls `ActionText::Attachable.from_node`, which locates the record from the node's sgid through Signed GlobalID, a `find` per attachment. So on a page that renders thirty full notes with three images each: 1. `with_rich_text_notes_and_embeds` removes the per-row rich-text and embeds queries; 2. the render still performs about ninety blob lookups by sgid, plus whatever each attachable partial queries itself; 3. the blob partial then builds a representation URL per image. Practical answers for list pages: - **Show excerpts**, not bodies: `to_plain_text` needs only the preloaded body, and attachments become short text such as `[etude.png]`. - **Cache rendered notes**: `ActionText::RichText` touches its record on change, so `cache lesson` keys stay fresh when notes are edited. - **Render full content on the show page**, where the per-embed cost is paid once. ## Making misses visible - `has_rich_text :notes, strict_loading: true` marks the association strict, so accessing `lesson.notes` without a preload raises `ActiveRecord::StrictLoadingViolationError` (or logs, if the app's violation action is `:log`). When the option is omitted it follows the model's `strict_loading_by_default`, which is `false` unless set. - A query-count assertion in a request test catches the regression when someone adds `notes` to a partial used by a list. ## A worked comparison | View code on 30 lessons | Without scope | `with_rich_text_notes` | |---|---|---| | `lesson.notes.to_plain_text` | 1 + 30 queries | 2 queries | | `lesson.notes.embeds.first` | 1 + 30 + embed queries per row | rich text preloaded; use `_and_embeds` to preload embeds too | | `<%= lesson.notes %>` with images | 1 + 30 + one lookup per image | 2 + one lookup per image | The last row is why full rich-text rendering belongs on detail pages or behind a cache. ## Choosing the scope in practice - An index that shows titles and dates only needs **no** rich-text preload at all; adding one loads bodies you never display. - An index with excerpts needs `with_rich_text_notes`; the plain text is computed from the preloaded body in Ruby. - A gallery of lesson images needs `with_rich_text_notes_and_embeds`, reading thumbnails from `notes.embeds` rather than rendering bodies. - A detail page that shows several rich-text attributes can use `with_all_rich_text` on the single-record query, or simply let each association load once. Preloading large bodies has its own cost: thirty long notes can be megabytes of HTML pulled into memory, so preload only what the page displays.

  • Does with_rich_text_notes_and_embeds remove the queries made while rendering embedded images?
    No. It preloads the `embeds` attachments and blobs, which helps code that reads `notes.embeds`. Rendering resolves each `<action-text-attachment>` from its sgid through Signed GlobalID, which finds the blob again per attachment. Avoid full rendering on list pages, or cache the rendered output.
  • Why does fragment caching on lesson work even though notes live in another table?
    `ActionText::RichText` declares `belongs_to :record, polymorphic: true, touch: true`, so saving the notes updates the lesson's `updated_at`. The lesson's cache key changes and `cache lesson` fragments are re-rendered without extra invalidation code.

  • Action Text stores the body on the lessons row, so listing lessons never adds queries
  • with_rich_text_notes also preloads every image embedded in the notes
  • with_rich_text_notes_and_embeds makes rendering embedded images query-free
  • with_all_rich_text preloads attachments declared with has_one_attached
  • strict_loading: true on has_rich_text validates that notes are present