Back to Course

Reading the Source · Card 12

What does delegated_type set up?

DHH's preferred shape for "an Entry can be a Message or a Comment." Less invasive than STI, more structured than raw polymorphic associations. Every Rails 6.1+ codebase has it somewhere.

The familiar line

A Hey-style example: an Entry is either a Message or a Comment.

class Entry < ApplicationRecord
  belongs_to :account
  delegated_type :entryable, types: %w[Message Comment]
end

class Message < ApplicationRecord
  include Entryable
end

class Comment < ApplicationRecord
  include Entryable
end

module Entryable
  extend ActiveSupport::Concern
  included do
    has_one :entry, as: :entryable, touch: true
  end
end

The question

What methods does delegated_type add to Entry, and what schema does it expect?

Take a moment. The shape is "Entry is a wrapper, the actual content lives in entryable." Think about: the polymorphic association, the predicates, the scopes.