In a Rails model, what does delegate :status, to: :rsvp, prefix: true, allow_nil: true generate, and what changes without allow_nil?
answer
- one generated method per name
- prefix: true uses the target name
- nil target raises ActiveSupport::DelegationError
- allow_nil: covers a nil target only
- private: true hides the method
basics
~10 sIt defines rsvp_status, which calls rsvp.status and returns nil when rsvp is nil. Without allow_nil: a nil rsvp raises ActiveSupport::DelegationError, a NoMethodError subclass naming the method and the nil target.
solid answer
~40 s`Module#delegate` is an Active Support class macro that writes a real method for each name. Here it defines `rsvp_status`, because `prefix: true` prepends the target's name (`prefix: :reply` would give `reply_status`). The method reads `rsvp` once and calls `status` on it. With `allow_nil: true`, a `nil` RSVP makes it return `nil`; without it, Rails raises `ActiveSupport::DelegationError`, a `NoMethodError` subclass whose message says `rsvp_status` was delegated to `rsvp` but `rsvp` is `nil`. `allow_nil:` only covers a nil target: if `rsvp` exists but lacks `status`, the plain `NoMethodError` still surfaces. `private: true` makes the generated methods private, and `to:` also accepts an instance variable, a constant or `:class`.
code
ruby · 11 linesclass Invitation < ApplicationRecord
has_one :rsvp
delegate :status, to: :rsvp, prefix: true, allow_nil: true
delegate :responded_at, to: :rsvp
end
invitation = Invitation.new
invitation.rsvp_status # => nil (no RSVP yet)
invitation.responded_at
# ActiveSupport::DelegationError:
# responded_at delegated to rsvp, but rsvp is nilgo deeper
Recall that delegate defines a method that calls the same method on another object, and that prefix: true puts the target's name in front.
Explain DelegationError versus allow_nil:, why allow_nil: does not rescue a missing method on a real target, and what private: and to: :class do.
Choose allow_nil: only where absence is a normal state, and use delegation to keep views off association chains so models can be refactored.
Judge when delegation helps encapsulation and when a long list of delegates signals that a model or presenter has the wrong boundaries.
## What the macro writes An invitation app keeps each guest's answer in a separate record: ```ruby class Invitation < ApplicationRecord belongs_to :event has_one :rsvp delegate :title, :starts_at, to: :event, prefix: true delegate :status, to: :rsvp, prefix: true, allow_nil: true end ``` `delegate` is defined on `Module` by **Active Support**, so any class or module can use it. It does not use `method_missing`: at class-load time it generates ordinary methods with `module_eval`, recording the `delegate` line as their source location so stack traces point back to it. The example above produces `event_title`, `event_starts_at` and `rsvp_status`, and `delegate` returns that list of method names. Each generated method evaluates the target **once** and calls the method on the result, forwarding arguments and blocks. So `invitation.rsvp_status` is `invitation.rsvp.status` with a nil rule attached, and a view can write `invitation.event_title` without reaching through two objects. ## The options | Option | Effect | Default | |---|---|---| | `to:` | the target: a method name, `:@ivar`, `:@@cvar`, a constant, or `:class` | required; missing it raises `ArgumentError` | | `prefix:` | `true` prepends the target name, a symbol or string prepends that word | no prefix | | `allow_nil:` | return `nil` instead of raising when the target is `nil` | raise | | `private:` | make the generated methods private | public | Two details are easy to miss: - `prefix: true` needs a method-like target name. `delegate :status, to: :@rsvp, prefix: true` raises `ArgumentError` when the class loads, because the automatic prefix only works when the target is a method name; pass a custom prefix such as `prefix: :reply` instead. - `private: true` suits a value a model needs internally, for example a guest count used only by a capacity check, without widening its public API. ## What happens when the target is `nil` This is the part interviewers probe. Without `allow_nil:` the generated method rescues the `NoMethodError` that calling a method on `nil` produces and, when the target really was `nil`, raises **`ActiveSupport::DelegationError`** instead (also reachable as `Module::DelegationError`). It is a subclass of `NoMethodError`, so existing `rescue NoMethodError` clauses still catch it, and its message names both sides: `rsvp_status delegated to rsvp, but rsvp is nil`. That is far easier to trace than a bare "undefined method for nil". With `allow_nil: true`, the method returns `nil` when the target is `nil`. The rules are narrower than the name suggests: 1. If the target is **not** `nil`, the call always happens, so a target that lacks the method still raises `NoMethodError`. `allow_nil:` is not a general rescue. 2. If the target is `nil` but `nil` itself responds to the method, the call goes through to `nil`: `delegate :to_s, to: :rsvp, allow_nil: true` returns `""`, not `nil`. ## Choosing `allow_nil:` deliberately `allow_nil:` is right when absence is a normal state: an invitation with no RSVP yet is expected, and the view can show "awaiting reply" for `nil`. It is wrong when absence is a bug: `belongs_to :event` is required by default, so an invitation without an event means corrupt data, and raising `DelegationError` surfaces it. Adding `allow_nil: true` everywhere "to be safe" turns data problems into blank cells. ## Other targets: the class, a constant, an instance variable `to:` is not limited to associations. `delegate :default_capacity, to: :class` lets an instance call a class method, which keeps per-event code from writing `self.class.default_capacity`. A constant works too (`delegate :include?, to: :ALLOWED_REPLIES`), and so does an instance variable in a plain Ruby object, `delegate :name, to: :@guest`, which is how form objects and presenters forward to what they wrap. Delegating to a module or class object directly requires it to be named, not anonymous. ## Related tools - **`delegate_missing_to :@event`** forwards every method the object does not define, through `method_missing`, which suits decorators and presenters; it also takes `allow_nil:`. - **Ruby's `Forwardable`** (`def_delegators`) is the standard-library counterpart. It works without Active Support but has no `allow_nil:` and no automatic target-name prefix. Why delegate at all? Views and controllers then depend on `invitation`'s interface instead of on the shape of its associations, so moving `status` onto the invitation itself later changes one line in the model rather than every template that reached through `rsvp`.
- How does `delegate_missing_to` differ from `delegate`?`delegate` generates named methods at class-load time; `delegate_missing_to :@event` defines `method_missing` and `respond_to_missing?` so every public method the object lacks is forwarded to the target. It suits a presenter wrapping a whole record, but it hides which methods exist and adds a `method_missing` hop to every call. Both raise `ActiveSupport::DelegationError` for a nil target unless `allow_nil: true` is passed.
- Why is `DelegationError` a subclass of `NoMethodError`, and why does that matter when you rescue it?Calling a method on `nil` normally raises `NoMethodError`, and because `DelegationError` subclasses it, existing `rescue NoMethodError` code still catches the delegated case while the message gets clearer. The flip side is that a broad `rescue NoMethodError` swallows delegation failures too, so rescue `ActiveSupport::DelegationError` specifically when that is what you mean.
- allow_nil: true makes the delegated method return nil for any NoMethodError.
- prefix: true names the generated method after the calling class, like invitation_status.
- delegate copies the target's value into the model when the class loads.
- Without allow_nil, a nil target simply makes the delegated method return nil.
- delegate comes from Ruby's Forwardable module, not from Active Support.