|
| 1 | +## ResourceController & model-level permitted_attributes |
| 2 | + |
| 3 | +This document explains how the `ResourceController` and `FriendlyResourceController` cooperate with model-level `permitted_attributes` to centralize strong parameter definitions. |
| 4 | + |
| 5 | +Key points |
| 6 | +- `ResourceController#permitted_attributes` returns `resource_class.permitted_attributes`. |
| 7 | +- Controllers inheriting from `ResourceController` or `FriendlyResourceController` use `resource_params` which delegates to `permitted_attributes` so you normally don't need to implement `*_params` methods in those controllers. |
| 8 | +- For controllers that do not inherit from `ResourceController`, prefer calling `Model.permitted_attributes` directly, for example: |
| 9 | + |
| 10 | +```ruby |
| 11 | +def conversation_params |
| 12 | + params.require(:conversation).permit(*BetterTogether::Conversation.permitted_attributes) |
| 13 | +end |
| 14 | +``` |
| 15 | + |
| 16 | +Composing nested permitted attributes |
| 17 | +- Instead of hard-coding nested permit lists, compose them by referencing other models' `permitted_attributes`. Example: |
| 18 | + |
| 19 | +```ruby |
| 20 | +class BetterTogether::Message < ApplicationRecord |
| 21 | + def self.permitted_attributes |
| 22 | + %i[id sender_id content _destroy] |
| 23 | + end |
| 24 | +end |
| 25 | + |
| 26 | +class BetterTogether::Conversation < ApplicationRecord |
| 27 | + def self.permitted_attributes |
| 28 | + [:title, { participant_ids: [] }, { messages_attributes: BetterTogether::Message.permitted_attributes }] |
| 29 | + end |
| 30 | +end |
| 31 | +``` |
| 32 | + |
| 33 | +Flow diagram |
| 34 | + |
| 35 | +```mermaid |
| 36 | +flowchart TD |
| 37 | + A[Request arrives at Controller] --> B{Controller type} |
| 38 | + B -->|Inherits ResourceController| C[resource_params -> resource_class.permitted_attributes] |
| 39 | + B -->|Custom Controller| D[Call Model.permitted_attributes directly] |
| 40 | + C --> E[Strong parameters applied] |
| 41 | + D --> E |
| 42 | + E --> F[Save/Update model] |
| 43 | +``` |
| 44 | + |
| 45 | +Why this pattern |
| 46 | +- Single source of truth for strong parameters. |
| 47 | +- Easier to compose nested attributes. |
| 48 | +- Reduces duplication and accidental permission mismatches. |
| 49 | + |
| 50 | +Where to update |
| 51 | +- If you add nested attributes, update the child model with `self.permitted_attributes` and reference it from the parent model. |
| 52 | +- When adding controllers, prefer inheriting `ResourceController` if the resource fits that pattern; otherwise call `Model.permitted_attributes` explicitly. |
0 commit comments