In a Rails app, what is a model concern, where does it live, and how would you share soft-delete behaviour across several models with one?
answer
- a module that extends ActiveSupport::Concern
- app/models/concerns is generated
- included do for scopes and callbacks
- class_methods do for class-level methods
- include SoftDeletable in each model
basics
~20 sA concern is a module that extends ActiveSupport::Concern, kept in app/models/concerns (or app/controllers/concerns). Its included block declares scopes and callbacks on the host, class_methods adds class methods, and plain defs become instance methods; each model then writes include SoftDeletable.
solid answer
~40 sA concern is an ordinary Ruby module that calls `extend ActiveSupport::Concern`, which gives it two hooks. Code in `included do ... end` runs inside the including class, so it can declare `scope :kept`, validations, callbacks or associations exactly as the model body would. Methods inside `class_methods do ... end` become class methods, and plain `def`s in the module become instance methods. `rails new` creates `app/models/concerns` and `app/controllers/concerns`, and each is its own autoload root, so `app/models/concerns/soft_deletable.rb` defines `SoftDeletable`, not `Concerns::SoftDeletable`. In a document-archive app, `Document`, `Folder` and `Note` each write `include SoftDeletable` and gain `kept` and `trashed` scopes, `soft_delete` and `restore`, as long as each table has a `deleted_at` column.
code
ruby · 10 linesclass Folder < ApplicationRecord
include SoftDeletable
has_many :documents
end
Folder.kept.count # WHERE deleted_at IS NULL
folder = Folder.first
folder.soft_delete # sets deleted_at
folder.trashed? # => true
Folder.purge_trashed_before(30.days.ago) # class method from class_methodsgo deeper
Recall the shape: extend ActiveSupport::Concern, an included block for scopes and callbacks, class_methods for class methods, defs for instance methods, and the generated concerns folders.
Explain why scope must sit in the included block, how class_methods becomes the class's methods, and what the concern assumes about the host's columns.
Show you would document and test a concern's contract with its hosts, and keep it to the host's public API.
Decide which shared behaviours deserve a concern at all, and how a team names and reviews them so concerns stay roles rather than a place to move code.
## The problem a concern solves A document-archive app lets users trash documents, folders and notes and restore them for thirty days. Each of those models needs the same pieces: a `deleted_at` column, scopes that hide or show trashed rows, methods to trash and restore a record, and a class-level purge for old trash. Copying that code into three models invites drift. A **concern** is the Rails way to write it once and mix it into each model. ## What a concern is A concern is a plain Ruby module that calls **`extend ActiveSupport::Concern`**. That one line adds three things a bare module lacks: - an **`included do ... end`** block, whose body runs in the context of the class that includes the module; - a **`class_methods do ... end`** block, whose methods become class methods of that class; - automatic handling of concerns that depend on other concerns. Everything else is ordinary module code: a `def` in the module body becomes an instance method of every including class. ```ruby # app/models/concerns/soft_deletable.rb module SoftDeletable extend ActiveSupport::Concern included do scope :kept, -> { where(deleted_at: nil) } scope :trashed, -> { where.not(deleted_at: nil) } end class_methods do def purge_trashed_before(time) trashed.where(deleted_at: ...time).destroy_all end end def soft_delete = update(deleted_at: Time.current) def restore = update(deleted_at: nil) def trashed? = deleted_at.present? end ``` ## Using it in a model ```ruby class Document < ApplicationRecord include SoftDeletable belongs_to :folder end ``` After `include SoftDeletable`, `Document.kept`, `Document.purge_trashed_before(30.days.ago)` and `document.soft_delete` all work, and so do the same calls on `Folder` and `Note` once they include it. Why the blocks matter: 1. `scope` is a class method of Active Record models. Written directly in the module body it would run on the module, which has no `scope` method; inside `included do` it runs on `Document`. 2. `purge_trashed_before` must be callable on the class, so it goes in `class_methods`. 3. `soft_delete`, `restore` and `trashed?` work on one record, so they are plain instance methods. ## Where concerns live `rails new` creates two folders with a `.keep` file each: | Folder | Typical contents | |---|---| | `app/models/concerns` | shared model roles: `SoftDeletable`, `Searchable`, `Taggable` | | `app/controllers/concerns` | shared controller behaviour, such as before_actions or `rescue_from` handlers | Each `concerns` folder is configured as its own root, so the file name maps to a top-level constant: `soft_deletable.rb` defines `SoftDeletable`. A concern used by only one model can also live in a folder named after it, for example `app/models/document/versioning.rb` defining `Document::Versioning`. ## Controller concerns work the same way The same module shape serves controllers. A concern in `app/controllers/concerns` can declare `before_action :set_folder` inside `included do`, add a `rescue_from` handler, or expose a helper with `helper_method`, and every controller that includes it gains them. The archive app might share a `FolderScoped` concern between `DocumentsController` and `NotesController`, so both load the current folder the same way. As with models, the `included` block runs with `self` set to the controller class, which is why those class-level macros work there. ## The contract a concern assumes A concern silently relies on its host. `SoftDeletable` assumes a `deleted_at` datetime column, so each including model needs a migration that adds it, ideally with an index if `kept` is used on large tables. Good concerns state that contract in a comment at the top, and keep to the host's public API (columns and public methods) rather than reaching into another concern's private helpers. ## Common mistakes - Forgetting `extend ActiveSupport::Concern`, after which `included do` raises `ArgumentError`, because Ruby's own `Module#included` hook expects the including class as an argument. - Writing `scope :kept, ...` at the top level of the module instead of inside `included do`. - Putting a class-level method in the module body and wondering why `Document.purge_trashed_before` is undefined. - Including the concern in a model whose table lacks `deleted_at`, which fails only when a scope or method first touches the column.
- Where would you put the `deleted_at` column, and how do you make sure every including model has it?Each model's table needs its own migration, such as `add_column :folders, :deleted_at, :datetime` plus an index if `kept` filters large tables. The concern cannot create columns. Document the requirement at the top of the concern, and cover it with a test that runs against every including model so a missing column fails in CI rather than in production.
- What goes wrong if `scope :kept` is written directly in the module body instead of inside `included do`?The module body runs once, when the file loads, with `self` being the module itself. `SoftDeletable` has no `scope` method, so loading the file raises `NoMethodError`. Inside `included do`, the same line runs with `self` set to `Document`, `Folder` or `Note`, which do have `scope`.
- A concern is a Rails class you inherit from, like ApplicationRecord.
- Scopes can be declared at the top level of a concern module.
- app/models/concerns/soft_deletable.rb must define Concerns::SoftDeletable.
- Including a concern adds the deleted_at column to the model's table.
- Plain defs in a concern become class methods of the including model.