How do you embed a non-file record, such as a repertoire Piece, inside Action Text content with ActionText::Attachable?
answer
- include ActionText::Attachable
- attachable_sgid, purpose attachable
- <action-text-attachment sgid=...>
- to_attachable_partial_path for display
- missing_attachable when the record is gone
basics
~10 sInclude 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.
solid answer
~40 sAdd `include ActionText::Attachable` to `Piece`. It provides `attachable_sgid`, a Signed GlobalID with purpose `"attachable"` and no expiry. The editor (or your code) inserts `<action-text-attachment sgid="..."></action-text-attachment>`; in Trix that is a `Trix.Attachment` created with `sgid` and `content` from your JavaScript, for example a mention picker. Only the sgid is stored. At render time `ActionText::Attachable.from_node` locates the record and renders `to_attachable_partial_path` (default `to_partial_path`, so `pieces/_piece`), so the lesson always shows the piece's current title and composer. `to_trix_content_attachment_partial_path` controls the editor preview, `attachable_plain_text_representation` controls `to_plain_text`, and a deleted record renders `to_missing_attachable_partial_path`, by default `action_text/attachables/missing_attachable`. Lookups are restricted to sgids signed for that purpose, so other signed ids cannot be replayed into content.
code
ruby · 14 linesclass Piece < ApplicationRecord
include ActionText::Attachable
def to_attachable_partial_path = "pieces/attachable"
def self.to_missing_attachable_partial_path = "pieces/missing"
def attachable_plain_text_representation(caption = nil)
"[#{title}]"
end
end
html = %(<p>Next week: <action-text-attachment sgid="#{piece.attachable_sgid}"></action-text-attachment></p>)
lesson.update!(notes: html)go deeper
Recall that Action Text can embed records as well as files, using an action-text-attachment tag with an sgid.
Explain ActionText::Attachable, attachable_sgid and its purpose, and the partial hooks for rendering, editor previews, plain text and missing records.
Weigh always-current embeds against per-embed lookups at render, lack of reverse tracking, and what the partial may expose to every reader of the content.
Decide whether references inside rich text should be Action Text attachables or modelled explicitly, considering reporting, permissions and long-term content migration.
## What an attachable is Action Text content can embed two kinds of things: **files**, which are Active Storage blobs, and **any record that can be found by a Signed GlobalID**. The second kind powers mentions, cards and live references. In the music-teacher app, a lesson's notes can reference a `Piece` from the repertoire, and the rendered note always shows the piece's current title, composer and grade. ```ruby class Piece < ApplicationRecord include ActionText::Attachable def to_attachable_partial_path = "pieces/attachable" def attachable_plain_text_representation(caption = nil) = "[#{title}]" end ``` ## The reference stored in the content `ActionText::Attachable#attachable_sgid` returns `to_sgid(expires_in: nil, for: "attachable")`: a signed, tamper-proof identifier of `gid://app/Piece/42` that never expires and is valid only for the `attachable` purpose. The content stores just this: ```html <p>Next week: <action-text-attachment sgid="BAh7CEkiCG..."></action-text-attachment></p> ``` The purpose matters: `ActionText::Attachable.from_attachable_sgid` locates records with `for: "attachable"`, so a signed id issued for a password reset or a blob's `signed_id` cannot be pasted into content and resolved. ## Inserting it - **From the editor**: your JavaScript (a Stimulus controller for an "insert piece" picker, say) fetches the piece's sgid and an HTML preview from an endpoint, then calls `editor.insertAttachment(new Trix.Attachment({ sgid, content }))`. Trix keeps the attachment as one unit the teacher can move or delete. - **From Ruby**: `ActionText::Content.new(html).append_attachables(piece)` or interpolating `piece.attachable_sgid` into HTML, as in seeds and tests. - **From an API client**: an endpoint returns `attachable_sgid` and the client inserts the tag itself. The editor preview is rendered with **`to_trix_content_attachment_partial_path`** (default `to_partial_path`); the HTML sent back to Trix is that partial's output. ## Rendering When `<%= @lesson.notes %>` renders: 1. Each `<action-text-attachment>` is passed to `ActionText::Attachable.from_node`, which tries the sgid first, then content attachments (HTML snippets inserted without an sgid), then remote images, and finally returns a `MissingAttachable`. 2. A found record is rendered with **`to_attachable_partial_path`**, by default `to_partial_path` (`pieces/_piece`), with the record available as the local `piece`. 3. The partial's HTML is placed inside the `<action-text-attachment>` element, then the whole content is sanitized. 4. A record that was deleted renders the class's **`to_missing_attachable_partial_path`**, by default `action_text/attachables/missing_attachable`; override it to show "Piece removed". | Hook | Default | Controls | |---|---|---| | `to_attachable_partial_path` | `to_partial_path` | rendered output in views and mailers | | `to_trix_content_attachment_partial_path` | `to_partial_path` | preview inside the editor | | `self.to_missing_attachable_partial_path` | `action_text/attachables/missing_attachable` | output when the sgid no longer resolves | | `attachable_plain_text_representation` | caption, or nothing | how the embed appears in `to_plain_text` | ## Trade-offs - **Always current**: renaming a piece updates every lesson that mentions it, with no content rewrite. - **A query per embed** at render time, because each sgid is located individually; cache rendered notes for pages that show many. - **Sanitizing applies**: the attachable partial's markup must fit the allow-list. - **Embeds are not tracked**: only blobs become `embeds`; mentioned records have no association back to the lessons that reference them, so finding "all lessons mentioning this piece" needs your own join model or a search over bodies. - **Authorization**: anyone who can view the lesson sees the rendered piece partial, so do not put private fields in it. ## Testing an attachable A model test can build content directly and assert on what Action Text resolves and renders: 1. Create a piece and a lesson whose notes contain `<action-text-attachment sgid="#{piece.attachable_sgid}">`. 2. Assert that `lesson.notes.body.attachables` returns `[piece]`. 3. Assert that `lesson.notes.to_plain_text` includes the piece's title from `attachable_plain_text_representation`. 4. Destroy the piece and assert that rendering shows the missing-attachable partial instead of raising. These four checks cover the resolution, plain-text and missing-record paths without a browser.
- Why does a Piece's attachable_sgid have no expiry while Active Storage URLs can expire?The sgid is stored permanently inside content and must still resolve years later, so `attachable_sgid` uses `expires_in: nil`. Its safety comes from the signature and the `attachable` purpose, not from a time limit, and it only identifies the record; what is shown is decided by the partial at render time.
- What does to_plain_text show for an embedded piece?`ActionText::Attachment#to_plain_text` calls the attachable's `attachable_plain_text_representation(caption)` when defined, otherwise it uses the attachment's caption. Without an override a piece mention may vanish from excerpts, so define it to return something like `[Moonlight Sonata]`.
- Action Text copies the piece's rendered HTML into the body when the lesson is saved
- Embedding a record requires it to have a has_one_attached file
- Any signed_id, such as a blob's signed_id, can be used in an action-text-attachment sgid
- Deleting a referenced Piece raises an error whenever old lessons are rendered
- Mentioned records are added to the rich text's embeds association