skip to content

In config/routes.rb, how do concern and concerns: let shows and episodes share the same nested reviews routes?

level: middleimportance: should knowfreq 30%

answer

  1. define once, attach many
  2. concerns: on the resources line
  3. concerns inside a block
  4. options reach a block parameter
  5. forward options with **options

basics

~10 s

concern :reviewable do resources :reviews end defines a reusable block of routes; resources :shows, concerns: :reviewable (or concerns :reviewable inside the block) draws those nested reviews routes under each resource that names it.

solid answer

~30 s

A routing concern names a chunk of the DSL so several resources can reuse it. `concern :reviewable do resources :reviews end` draws nothing by itself; `resources :shows, concerns: :reviewable` and `resources :episodes, concerns: :reviewable` each draw the reviews routes nested under that resource, giving `show_reviews_path(show)` and `episode_reviews_path(episode)`, both handled by `ReviewsController`. Inside a block you can write `concerns :reviewable` instead. Options passed at the use site, such as `concerns :reviewable, only: :index`, reach the block's parameter; in Rails 8.1 forward them as keywords, `resources :reviews, **options`, because a positional options hash is deprecated. An unknown concern name raises `ArgumentError`.

code

ruby · 14 lines
ruby
# config/routes.rb
Rails.application.routes.draw do
  concern :reviewable do |options|
    resources :reviews, **options
  end

  resources :shows, concerns: :reviewable
  resources :episodes do
    concerns :reviewable, only: [:index, :create]
  end
end

# GET  /shows/3/reviews     -> reviews#index  show_reviews_path(show)
# POST /episodes/42/reviews -> reviews#create episode_reviews_path(episode)

go deeper

for a junior

Know that concern defines a named block of routes and that concerns: attaches it to a resource, drawing nested routes there.

for a middle

Explain the routes and helpers a concern produces per parent, how use-site options reach the block, and why they are forwarded with **options in Rails 8.1.

for a senior

Judge when shared nested routes justify a concern and plan for the single controller that must resolve several parent types.

for a principal

Keep the route file's abstractions proportionate: concerns for routes shared across many parents, plain blocks everywhere else.

## The duplication concerns remove A podcast host lets listeners review both whole **shows** and individual **episodes**. Without help, `config/routes.rb` repeats the same nested block: ```ruby resources :shows do resources :reviews, only: [:index, :create] end resources :episodes do resources :reviews, only: [:index, :create] end ``` Every change to the reviews routes now has to be made twice. A **routing concern** gives that block a name, defines it once, and lets each resource opt in. It has nothing to do with model concerns built on `ActiveSupport::Concern`; the shared word is the only link. ## Defining and using a concern ```ruby concern :reviewable do resources :reviews, only: [:index, :create] end resources :shows, concerns: :reviewable resources :episodes, concerns: :reviewable ``` - **`concern`** registers a block under a name and draws **nothing** at that point. - **`concerns:`** on a `resources` or `resource` line runs the named concerns inside that resource, as if their contents had been typed in its block. It takes one name or an array: `concerns: [:reviewable, :downloadable]`. - **`concerns`** as a method does the same from inside a block: `resources :shows do concerns :reviewable end`. It also works in a `namespace` or `scope` block. - A name that was never defined raises `ArgumentError` ("No concern named ... was found!") when the routes load. The result is ordinary nested routing: `/shows/:show_id/reviews` with `show_reviews_path(show)` and `/episodes/:episode_id/reviews` with `episode_reviews_path(episode)`, both dispatched to one `ReviewsController`, which reads whichever parent key arrived. ## What gets drawn With the two `concerns: :reviewable` lines above, `bin/rails routes -c reviews` would list two nested groups, one per parent: | Verb | Path | Helper | |---|---|---| | GET | `/shows/:show_id/reviews` | `show_reviews_path(show)` | | POST | `/shows/:show_id/reviews` | `show_reviews_path(show)` | | GET | `/episodes/:episode_id/reviews` | `episode_reviews_path(episode)` | | POST | `/episodes/:episode_id/reviews` | `episode_reviews_path(episode)` | Every row dispatches to `reviews#index` or `reviews#create`. Each group follows the ordinary nesting rules, so it is exactly what the hand-written nested blocks drew, with the definition kept in one place. ## Passing options into a concern The use site may pass options, and a block that declares a parameter receives them: ```ruby concern :reviewable do |options| resources :reviews, **options end resources :shows, concerns: :reviewable resources :episodes do concerns :reviewable, only: :index end ``` Here shows get every review route and episodes get only `index`. With `concerns:` on a resources line no options are passed, so the block receives an empty hash. **Forward the hash as keywords.** Older examples, including the routing API's own comment, write `resources :reviews, options`. In Rails 8.1 that passes a positional hash, which `resources` still accepts but reports with a deprecation warning saying hash arguments will be removed in Rails 8.2. `**options` passes the same values as keyword arguments, the form the DSL expects. ## Callable concerns The second argument of `concern` may be any object that responds to `call(mapper, options)` instead of a block. That moves larger reusable route sets out of the routes file into a plain Ruby class, which receives the mapper and calls `mapper.resources ...` on it. It is rarely needed; a block covers most apps. ## When concerns help and when they do not - **Help**: the same nested routes on several parents (reviews, comments, attachments, likes), especially when their options must stay in sync. - **Do not help**: a block used once, where a name adds indirection without saving anything. - **Watch the controller**: one `ReviewsController` now serves several parents and must work out which parent key it received, often through a small lookup per parent type. - **Watch the reader**: `bin/rails routes -c reviews` shows the expanded result, which is quicker than tracing which resources include which concern. ## Summary for the interview Define with `concern :name do ... end`, attach with `concerns: :name` or `concerns :name`, pass options through a block parameter, and forward them with `**options` on Rails 8.1.

  • How does ReviewsController know whether a request came from a show or an episode?
    The nested routes deliver different parent keys: `params[:show_id]` for `/shows/:show_id/reviews` and `params[:episode_id]` for `/episodes/:episode_id/reviews`. The controller checks which key is present and loads that parent. Some apps pass a `defaults:` value through the concern's options instead, so the controller reads an explicit parent type.
  • A colleague's concern block calls resources :reviews, options and the logs fill with deprecation warnings on Rails 8.1. What changed?
    Rails 8.1's routing DSL takes options as keyword arguments and treats a trailing positional hash as a deprecated form, warning that it will be removed in Rails 8.2. Changing the call to `resources :reviews, **options` passes the same values as keywords and silences the warning.

  • concern :reviewable draws the reviews routes at the point it is defined
  • Routing concerns are modules built with ActiveSupport::Concern
  • resources :reviews, options is the current way to forward concern options
  • Using an undefined concern name is silently ignored
  • Each parent needs its own Shows::ReviewsController and Episodes::ReviewsController

Assumes Rails 8.1 (checked against 8.1.4), where routing DSL methods warn when given a positional options hash and the hash form is slated for removal in 8.2.