With Pundit, how does `permitted_attributes` let forum moderators set a post's pinned flag while authors may edit only title and body?
answer
- policy method returns the allowed keys
- permitted_attributes_for_#{action} wins
- param_key from the model name
- pundit_params_for can be overridden
- action means the submitting action: update
basics
~10 sDefine permitted_attributes in PostPolicy to return the keys the current user may write, such as adding :pinned for moderators. The controller's permitted_attributes(@post) fetches params[:post] and permits exactly those keys.
solid answer
~30 sThe policy decides which fields a user may write: `PostPolicy#permitted_attributes` returns `[:title, :body]`, plus `:pinned` when `user.moderator?`. In the controller, `permitted_attributes(@post)` builds the policy, calls `permitted_attributes_for_#{action_name}` if the policy defines it (for example `permitted_attributes_for_create`), otherwise `permitted_attributes`, and passes the keys to `permit` on `pundit_params_for(@post)`. That method requires the record's param key, `post` from `Post.model_name`, so a missing key raises `ActionController::ParameterMissing`. An author who submits `pinned` simply has it dropped. The action is the one receiving the form, so define `_for_update`, not `_for_edit`. Override `pundit_params_for` when the payload lives elsewhere, such as JSON:API's `data.attributes`.
code
ruby · 21 linesclass PostPolicy < ApplicationPolicy
def permitted_attributes
base = [:title, :body]
user&.moderator? ? base + [:pinned, :locked] : base
end
def permitted_attributes_for_create
[:title, :body, :topic_id]
end
end
class PostsController < ApplicationController
def update
@post = authorize Post.find(params[:id])
if @post.update(permitted_attributes(@post))
redirect_to @post
else
render :edit, status: :unprocessable_content
end
end
endgo deeper
Know that a policy can list the fields a user may write and that permitted_attributes(@post) applies that list to the params.
Explain the action-specific method lookup, the param key from model_name, ParameterMissing and the pundit_params_for override.
Keep field rules, the authorize check and the form's visible fields consistent, and test that low-privilege users cannot write privileged keys.
Judge when per-role field lists in policies stop scaling and need a different representation of field permissions.
## The problem In a community forum, the post form is shared: authors edit **title** and **body**, moderators can also set **pinned** and **locked**. A single strong-parameters list in the controller either lets authors pin their own posts or stops moderators from pinning. The rule "who may write which field" depends on the user, which is exactly what a Pundit policy already knows. ## The policy side A policy can define: - `permitted_attributes`: the keys this user may write for any action; - `permitted_attributes_for_<action>`: the keys for one controller action, which take precedence when present, for example `permitted_attributes_for_create`. Both return the same shape you would pass to `permit`: symbols, and hashes for arrays or nested keys such as `{ tag_ids: [] }`. Because they are ordinary methods on the policy, they can read `user` and `record`. ## The controller side, step by step `permitted_attributes(record, action = action_name)` in `Pundit::Authorization`: 1. builds or reuses the policy for `record` (the same memoised object `authorize` used); 2. picks the method: `permitted_attributes_for_#{action}` if the policy responds to it, else `permitted_attributes`; 3. calls `pundit_params_for(record)`, which by default is `params.require(PolicyFinder.new(record).param_key)`; 4. calls `permit(*keys)` on that and returns the permitted parameters. The **param key** comes from the model: `Post.model_name.param_key` is `"post"`, so a form built with `form_with model: @post` lines up. For a model namespaced in a plain module, such as `Forum::Post`, `param_key` is typically `forum_post`. ## Traps worth knowing | Situation | What happens | |---|---| | The form submits without a `post` key | `ActionController::ParameterMissing`, a 400 response | | An author submits `pinned` | the key is not permitted and is dropped (logged or raised per the app's unpermitted-parameters setting) | | Policy defines `permitted_attributes_for_edit` | ignored on submit, because the form posts to `update` | | A custom `pin` action | `permitted_attributes(@post, :update)` reuses the update list | The `_for_edit` trap is common because the edit page and the update request feel like one feature. Pundit keys on the action that **receives** the parameters. ## Overriding where the parameters come from `pundit_params_for(record)` is the seam. Override it in a controller when the payload is not nested under the model's key: 1. JSON:API style: return `params.fetch(:data, {}).fetch(:attributes, {})`; 2. optional nesting: return `params.fetch(param_key, {})` so a missing key gives an empty set instead of a 400. Rails 8's `params.expect` does not appear here: Pundit's helper builds on `require` and `permit` internally, and the override must return an `ActionController::Parameters` that `permit` can be called on. ## Arrays, nested keys and forms The list a policy returns goes straight into `permit`, so every strong-parameters shape works: - arrays of scalars: `{ tag_ids: [] }`; - nested hashes: `{ poll_attributes: [:question, { options: [] }] }`; - conditional additions: append moderator-only keys only when `user&.moderator?`. The form should agree with the policy. When a moderator-only checkbox is rendered for everyone, authors submit it and it is silently dropped, which looks like a bug to them. Rendering the field only when the policy permits it keeps the page and the rule in step. ## Keeping the decision in one place - Pair it with `authorize`: `permitted_attributes` says **which fields**, `authorize @post` says **whether** the update is allowed at all. Neither replaces the other. - Keep the view consistent: the form can show the pinned checkbox only when `policy(@post).permitted_attributes.include?(:pinned)`. - Test the policy method directly: a member's list must not contain `:pinned`.
- Does permitted_attributes replace calling authorize in the update action?No. It filters which keys reach the model; it never refuses the request. A member could still update someone else's post with the allowed keys unless `authorize @post` checks `update?` first. It also does not set the flag `verify_authorized` looks for.
- How would you accept a JSON:API payload with Pundit's permitted_attributes?Override `pundit_params_for(record)` in that controller to return `params.fetch(:data, {}).fetch(:attributes, {})`. `permitted_attributes` still asks the policy for the keys and calls `permit` on whatever that method returns, so the policy stays unchanged.
- permitted_attributes_for_edit controls what the update form may submit
- An author submitting pinned gets a Pundit::NotAuthorizedError
- permitted_attributes also checks whether the update is allowed
- Pundit reads the param key from the controller name
- The policy must return a Hash of attribute values