skip to content

In Rails 8.1, how do you retire an Active Record association safely with deprecated: true, and what counts as using it?

level: seniorimportance: nice to knowfreq 15%

answer

  1. new in 8.1 associations
  2. mark first, remove later
  3. warn, raise or notify
  4. dependent: and touch: side effects report
  5. DeprecatedAssociationError in raise mode

basics

~20 s

Rails 8.1 lets you mark has_many :swimlanes, deprecated: true. Every use, from generated methods and executed preloads to through associations and dependent: or touch: side effects, is then reported as a warning, exception or notification before you remove it.

solid answer

~30 s

Since Rails 8.1, `deprecated: true` on an association makes Active Record report each use: calls to its generated methods (`swimlanes`, `swimlane_ids=`), nested attribute assignment, use of a through association built on it, executed queries that preload, eager load or join it, and the side effects of its `dependent:` or `touch:` options. Declarations and unexecuted relations do not report. `config.active_record.deprecated_associations_options` picks `:warn` (the default, to the Active Record logger), `:raise` (`ActiveRecord::DeprecatedAssociationError`) or `:notify` (the `deprecated_association.active_record` event), plus `backtrace:`. The workflow: mark it, raise in tests, watch production warnings, move any cascade or touch behaviour elsewhere, then delete the association.

code

ruby · 10 lines
ruby
# config/environments/test.rb
config.active_record.deprecated_associations_options = { mode: :raise }

# config/environments/production.rb
config.active_record.deprecated_associations_options = { mode: :notify }

# config/initializers/deprecated_associations.rb
ActiveSupport::Notifications.subscribe("deprecated_association.active_record") do |event|
  Rails.logger.info(event.payload[:message])
end

go deeper

for a junior

Recall that Rails 8.1 can mark an association deprecated: true and that using it then logs a warning by default.

for a middle

Explain what counts as usage, including executed preloads, through associations and dependent: or touch: side effects, and what does not.

for a senior

Run the retirement: raise in tests, notify or warn in production, move cascades and touches elsewhere, then delete the association and its schema later.

for a principal

Use staged deprecation as a team practice for removing model surface, with observation windows and owners, rather than big-bang deletions.

## The problem Removing an association from a large Rails app is risky. `has_many :swimlanes` on `Board` may be used in places a text search will not find: a view calling `board.swimlane_ids`, a `preload(:swimlanes)` built from a symbol, a nested-attributes form, a `has_many :through` that goes through it, or a `dependent:` cascade that quietly deletes swimlanes when boards are destroyed. Delete the line and some of those break at runtime, perhaps only in production. Rails 8.1 adds a way to retire an association in steps: mark it deprecated, collect every place that uses it, then remove it. ```ruby class Board < ApplicationRecord has_many :columns has_many :swimlanes, deprecated: true # replaced by columns end ``` ## What counts as usage Once marked, Active Record reports a usage whenever: - any generated method runs: `swimlanes`, `swimlanes=`, `swimlane_ids`, `swimlane_ids=`, `swimlanes.build` and the rest; - nested attributes for it are assigned; - a **through** association that goes through it is used, even if the through association itself is not deprecated; - a query that refers to it **executes**: `preload(:swimlanes)`, `eager_load(:swimlanes)`, `joins(:swimlanes)`; - a board is destroyed and the association has a `dependent:` option, because that side effect would disappear with the association; - a record is saved or destroyed and the association has a `touch:` option, for the same reason. ## What does not report Because associations are resolved lazily, some references are just symbols until used: 1. declaring `has_many :lanes_cards, through: :swimlanes`; 2. calling `accepts_nested_attributes_for :swimlanes`; 3. another association declaring `inverse_of: :swimlanes`; 4. declaring `validates_associated :swimlanes` (running the validation does report); 5. building `Board.includes(:swimlanes)` without executing it; 6. reflection: `Board.reflect_on_association(:swimlanes)`. ## Reporting modes Configure with `config.active_record.deprecated_associations_options`, a hash with `:mode` and `:backtrace`. The default is `{ mode: :warn, backtrace: false }`. | Mode | What happens on usage | |---|---| | `:warn` (default) | a warning in the Active Record logger, with the application line that triggered it | | `:raise` | raises `ActiveRecord::DeprecatedAssociationError` with a clean backtrace | | `:notify` | publishes the `deprecated_association.active_record` notification with `:reflection`, `:message` and `:location` (plus `:backtrace` when enabled) | A message reads like "The association Board#swimlanes is deprecated, the method swimlane_ids was invoked (app/views/boards/show.html.erb:12)". With `backtrace: true`, warnings include a cleaned backtrace and notifications gain a `:backtrace` key; exceptions always carry one. ## A retirement workflow 1. Mark the association `deprecated: true` and ship. Nothing breaks; production logs start collecting warnings. 2. In the test environment, set `mode: :raise`, so any test that still exercises the association fails with a precise location. 3. Optionally, in production, use `mode: :notify` and subscribe to the event to aggregate usages by location. 4. Replace each usage. Pay special attention to `dependent:` and `touch:` reports: they mean removing the association also removes a cascade or a timestamp update you may still need, so move that behaviour somewhere explicit first. 5. When the logs and the suite are quiet, delete the association, and later the column or table, in a separate migration. ## Why not just grep? Associations are reached through symbols and generated methods, so usages hide in `preload(:swimlanes)` strings built at runtime, in `*_ids` form fields, in through chains and in callbacks that never mention the name. Runtime reporting finds what static search misses, and the `dependent:` and `touch:` reports catch side effects no search would reveal. ## Where the location comes from Each report names the application-level line that triggered it, such as a view or a service object, not a line inside Active Record. Rails computes it with the Active Record backtrace cleaner, which in a Rails app is by default the same as `Rails.backtrace_cleaner`, so framework and gem frames are filtered out. That single location is included even in the default `:warn` mode; `backtrace: true` adds the whole cleaned stack. For through associations, the message also says which through association pulled the deprecated one in, so a report about `swimlanes` can point at the `lanes_cards` call that used it. ## Limits Deprecation reporting tells you that code ran, not that it is the only code; paths that never execute during observation stay silent. Combine it with a search and with test coverage before the final removal.

  • Why does destroying a board report a deprecated has_many :swimlanes, dependent: :destroy even if no code calls swimlanes?
    The `dependent:` cascade is itself a use: removing the association would stop swimlanes being destroyed with their board. Rails reports it so you move that cleanup somewhere explicit, or decide it is no longer needed, before deleting the association.
  • Does Board.includes(:swimlanes) report a usage of a deprecated association?
    Not when the relation is built, only when it executes. Until then it is a relation holding a symbol; running the query, for example by calling `to_a` or iterating it, triggers the report.

  • deprecated: true removes the association's methods immediately.
  • The default mode raises ActiveRecord::DeprecatedAssociationError.
  • Declaring accepts_nested_attributes_for on it triggers a warning.
  • Only direct calls like board.swimlanes are reported, not queries.
  • deprecated: on associations has existed since Rails 7.1.

Assumes Rails 8.1, where deprecated: on associations and config.active_record.deprecated_associations_options were introduced.