skip to content

In Active Record, how does belongs_to with polymorphic: true pair with as: on the other models, and what does it cost you?

level: middleimportance: should knowfreq 52%

answer

  1. one association, many target tables
  2. taggable_id plus taggable_type
  3. as: :taggable names the interface
  4. source_type: for through queries
  5. no foreign key constraint possible

basics

~10 s

belongs_to :taggable, polymorphic: true stores taggable_id and taggable_type (the target's class name), and each target declares has_many :taggings, as: :taggable. The cost: no database foreign key, class names in your data, and no build_taggable.

solid answer

~40 s

A polymorphic `belongs_to :taggable, polymorphic: true` needs two columns, `taggable_id` and `taggable_type`; assigning a book writes its id and the string `"Book"`. Each model that can be tagged declares `has_many :taggings, as: :taggable`, and Active Record filters on both columns. To reach books from a tag through the join you add `source: :taggable, source_type: "Book"` to the `has_many :through`. The trade-offs: a database foreign key cannot point at several tables, renaming a model breaks stored type strings, Rails generates no `build_taggable` or `create_taggable` because it cannot know the class, and joins need a concrete type. Use it for shared, same-shaped behaviour such as tags or comments, not for two known parents.

code

ruby · 9 lines
ruby
tag = Tag.find_by!(name: "signed copy")

book.taggings.create!(tag: tag)          # taggable_id = book.id, taggable_type = "Book"
author.taggings.create!(tag: tag)        # taggable_type = "Author"

Tagging.last.taggable                    # => the Author (class read from taggable_type)
tag.books                                # needs source_type: "Book" on the through

Tagging.new.respond_to?(:build_taggable) # => false, the class is unknown

go deeper

for a junior

Recall the two columns, which side gets polymorphic: true and which gets as:, and what the type column holds.

for a middle

Explain how reads and writes use the type string, why source_type: is needed on a through association, and why build_taggable is not generated.

for a senior

Judge the trade-off: lost referential integrity and data-coupled class names versus one shared table; know the separate-keys alternative and when it wins.

for a principal

Decide at the schema level how much integrity you trade for flexibility, and plan for renames: class names stored in data turn refactors into data migrations.

## What a polymorphic association is A **polymorphic** `belongs_to` lets one model point at rows of several different models through a single association. In the used-bookstore catalogue, staff tag both books and authors ("signed copy", "local author"), and one `taggings` table serves both: ```ruby class Tagging < ApplicationRecord belongs_to :tag belongs_to :taggable, polymorphic: true end class Book < ApplicationRecord has_many :taggings, as: :taggable end class Author < ApplicationRecord has_many :taggings, as: :taggable end ``` `polymorphic: true` goes on the `belongs_to` side. `as: :taggable` goes on each `has_many` or `has_one` side and names the **interface** the other models agree to. ## The two columns A polymorphic `belongs_to :taggable` needs two columns on `taggings`: - `taggable_id`, the primary key of the target row; - `taggable_type`, a string holding the target's **class name**. Assigning `tagging.taggable = book` writes `taggable_id = book.id` and `taggable_type = "Book"`. Reading `tagging.taggable` turns the type string back into a class and runs a query against that class's table. From the other side, `book.taggings` queries `WHERE taggable_id = ? AND taggable_type = 'Book'`, so an index on both columns together is the usual companion. The `foreign_type:` option renames the type column if your schema differs. ## What the type column stores The value is the class's **polymorphic name**, which by default is the full class name of the **base class**: 1. A namespaced model stores the namespace too: `Catalog::Book` is stored as `"Catalog::Book"`. 2. An STI subclass stores its base class: a `RareBook < Book` is stored as `"Book"`, so the `Book` side's `has_many ... as:` finds it. 3. Renaming or moving a model breaks every stored row until you migrate the type strings; the API docs call this out on the `polymorphic` option. ## Reaching through a polymorphic link To go from a tag to its books, a `has_many :through` must say which type it wants: ```ruby class Tag < ApplicationRecord has_many :taggings has_many :books, through: :taggings, source: :taggable, source_type: "Book" has_many :authors, through: :taggings, source: :taggable, source_type: "Author" end ``` Without `source_type:`, Active Record raises `ActiveRecord::HasManyThroughAssociationPolymorphicSourceError`, because a through query has to join one concrete table. `class_name:` would not help here: it is ignored on `:through` associations and not even accepted on a polymorphic `belongs_to`. ## What it costs you | Cost | Why | |---|---| | No database foreign key constraint | a constraint references one table; `taggable_id` may point at several | | Class names live in your data | renames and namespace moves need a data migration | | No `build_taggable` / `create_taggable` | Rails cannot know which class to instantiate | | Joins need a concrete type | a single SQL join cannot target "whatever table the row names" | | Wider rows and a composite index | every row repeats a type string | The generated methods table in the API docs makes the constructor gap explicit: a polymorphic `belongs_to` gets `taggable`, `taggable=`, `reload_taggable` and the change-tracking predicates, but no `build_` or `create_` methods. ## Polymorphic has_one and has_many `as:` works on both collection and singular sides. A model could declare `has_one :tagging, as: :taggable` as easily as `has_many :taggings, as: :taggable`; in both cases Active Record adds `taggable_type = 'Book'` (for a book) to the query and sets it when you build through the association, so `book.taggings.build(tag: tag)` returns a tagging with both `taggable_id` and `taggable_type` already filled. On the `belongs_to` side you assign a record, never the two columns by hand, and Active Record keeps them consistent. ## When to reach for it, and when not Polymorphism fits when many unrelated models share **one behaviour with the same shape**: tags, comments, audit entries, attachments. It is a poor fit when only two or three known parents exist and integrity matters more than flexibility. Then the plainer design is separate nullable key columns (`book_id`, `author_id`) with a check that exactly one is set, which keeps real foreign key constraints. Rails also offers `delegated_type` for the case where the varying models are kinds of one entity; that pattern belongs to the inheritance topic. ## In an interview Name both columns, place `polymorphic: true` and `as:` on the right sides, mention `source_type:` for through queries, and give at least two costs, with the missing foreign key constraint first. A candidate who can explain why `build_taggable` does not exist has understood the mechanism rather than memorised the syntax.

  • What does a polymorphic type column store for an STI subclass or a namespaced model?
    The base class's full name by default: a `RareBook < Book` is stored as `"Book"`, and `Catalog::Book` as `"Catalog::Book"`. Storing the base class is what lets the `has_many ... as:` on the base model find STI rows. Renaming either class means migrating the stored strings.
  • When would you choose separate book_id and author_id columns over a polymorphic link?
    When the set of parents is small and fixed and integrity matters. Separate nullable keys allow real foreign key constraints and plain joins; you add a check that exactly one is present. Polymorphism pays off when many models share the same behaviour.

  • A polymorphic belongs_to needs only taggable_id; Rails infers the class.
  • You can add a database foreign key from taggable_id to each target table.
  • class_name: "Book" on the through association replaces source_type:.
  • polymorphic: true goes on the has_many side and as: on the belongs_to.
  • Renaming a model is safe because type columns store table names.