Skip to content

Generate typed model / klass on per-model relation classes - #2783

Open
kamipo wants to merge 1 commit into
Shopify:mainfrom
kamipo:relation-model-klass-sig
Open

kamipo wants to merge 1 commit into
Shopify:mainfrom
kamipo:relation-model-klass-sig

Conversation

@kamipo

@kamipo kamipo commented Nov 24, 2026

Copy link
Copy Markdown

Motivation

Closes #2782.

ActiveRecord::Relation#model (and its alias klass) is T.untyped, so inside a scope body, where self is the relation, calls like model.some_class_method are unchecked. This can't be typed generically on ActiveRecord::Relation: T.class_of(Elem) isn't allowed, and T::Class[Elem] doesn't resolve the model's class methods. Only the per-model generated classes know the concrete model constant.

Implementation

create_relation_class, create_association_relation_class and create_collection_proxy_class now also generate:

sig { returns(T.class_of(::Post)) }
def klass; end

sig { returns(T.class_of(::Post)) }
def model; end
  • The GroupChain classes inherit from PrivateRelation / PrivateAssociationRelation, so they get the methods without changes. The WhereChain classes aren't relations.
  • STI subclasses get their own generated classes, and Sub.all.model is Sub, so the per-model type is correct.
  • For a collection proxy, post.comments.model is Comment, which matches Comment::PrivateCollectionProxy.
  • Code that used these values as T.untyped may start reporting type errors.

The compiler docstring and the generated manual are updated.

Tests

Updated the expected RBI in spec/tapioca/dsl/compilers/active_record_relations_spec.rb. That spec and active_record_scope_spec.rb pass, and rubocop and srb tc are clean.

🤖 Generated with Claude Code

`ActiveRecord::Relation#model` (and its alias `klass`) is untyped in the
gem RBI, and it can't be typed generically on `ActiveRecord::Relation`
because `T.class_of(Elem)` isn't allowed. The per-model generated
classes know the concrete model, so generate the sigs there.

Closes Shopify#2782

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kamipo
kamipo requested a review from a team as a code owner November 24, 2026 09:59

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ActiveRecordRelations: generate typed model / klass on per-model relation classes

1 participant