Quick start · Why · Adopting on a live API · Guide · Reference · Comparison · Changelog
params.permit answers one question: which keys may pass? A Permittable contract, declared once on the controller class, also casts each field to a declared type, validates it, applies defaults, and turns every failure into a machine-readable 422 that names the offending parameter.
class UsersController < ApplicationController
include Permittable
permit_params :create, :update, root: :user, model: User do
required :name, :string, length: 1..80, normalize: :squish
required :email, :string, format: URI::MailTo::EMAIL_REGEXP, normalize: :email
optional :age, :integer, in: 18..120
optional :ssn, :string, sensitive: true # auto-redacted from logs
optional :plan, :string, in: %w[free pro], default: "free"
array :tag_names, of: :string, length: 0..10, virtual: true
optional :address do
required :city, :string
optional :zip, :string, format: /\A\d{5}\z/
end
end
def create
User.create!(permitted_params) # cast, validated, defaulted
end
endA violating request never reaches your action:
{ "success": false,
"error": { "message": "Invalid parameters: user.age (inclusion)",
"code": "invalid_parameters",
"details": [{ "param": "user.age", "code": "inclusion" }] } }Quick start
# Gemfile
gem "permittable"class ApplicationController < ActionController::Base
include Permittable
end
class OrdersController < ApplicationController
permit_params :create, root: :order, model: Order do
required :sku, :string
optional :quantity, :integer, in: 1..99, default: 1
optional :notes, :string, length: 0..500
end
def create
Order.create!(permitted_params)
end
endThat is the whole integration. Violations render the 422 automatically, model: Order checks the fields against the orders table when the class loads, and every rejected request emits an invalid_parameters.permittable notification.
Naming note: some legacy stacks (InheritedResources) define their own
permitted_params. Don't include both on one controller.
Why
Here is what the contract above replaces. Every Rails codebase has a version of this, and no two of them agree on the error shape:
def create
attrs = params.require(:user).permit(:name, :email, :age, :plan)
if attrs[:age].present?
age = Integer(attrs[:age], exception: false)
return render(json: { error: "age must be a number" }, status: 422) if age.nil?
return render(json: { error: "age must be 18..120" }, status: 422) unless (18..120).cover?(age)
attrs[:age] = age
end
unless attrs[:email].to_s.match?(URI::MailTo::EMAIL_REGEXP)
return render(json: { error: "email is invalid" }, status: 422)
end
attrs[:plan] = "free" if attrs[:plan].blank?
User.create!(attrs)
endparams.permit |
params.expect (Rails 8) |
Permittable | |
|---|---|---|---|
| Filters unknown keys | ✅ | ✅ | ✅ |
| Requires a root key | via require
|
✅ | ✅ |
| Casts to a declared type | ❌ | ❌ | ✅ |
| Validates bounds, formats, sets | ❌ | ❌ | ✅ |
| Supplies defaults | ❌ | ❌ | ✅ |
| Machine-readable error details | ❌ | ❌ | ✅ |
| Reshapes output | ❌ | ❌ | ✅ |
| Checked against your schema at boot | ❌ | ❌ | ✅ |
| Exports OpenAPI / JSON Schema | ❌ | ❌ | ✅ |
| Report-only rollout mode | ❌ | ❌ | ✅ |
| Drafts contracts from your schema | ❌ | ❌ | ✅ |
| Works outside controllers | ❌ | ❌ | ✅ |
Every option in this space is good software, and Permittable is not always the right one. The comparison covers params.expect, rails_param, dry-validation, typed_params and rswag, the cases where each is the better choice, benchmarks, and migration costs.
How it works: a contract is data
A contract is declared once at the class level, frozen, inheritable, and introspectable. It is not code that runs inside your action, so more than the validator can read it:
The principles that fall out of it:
-
Strict, never lenient.
"abc"is never0. A value the type cannot faithfully represent is a violation, not a guess. -
niland""are absent. Absent optionals are omitted from the result, so partial updates never nil-out columns. - Mistakes fail at class load. A malformed contract, a default that violates its own field, or a column that no longer exists fails the boot, never the request.
-
The request's
paramsis never mutated. Reshaping happens on the validated copy. -
Exports never guess. Anything JSON Schema cannot represent stays visible as an
x-permittable-*extension instead of being mistranslated. -
One dependency.
activesupportis the only runtime requirement. Rails, ActionPack, and ActiveRecord are optional integration points.
Adopting on a live API
You cannot know what the 422s would break until you enforce them, and you dare not enforce them until you know. Old app versions, third-party integrations and forgotten cron jobs all send what they send. The recipe:
-
Draft.
bin/rails permittable:generatewrites a first contract for every controller from the model's columns and theparams.permit/params.expectcalls already in the source. -
Monitor. Deploy with
PERMITTABLE_MODE=monitor. Behaviour is unchanged; every would-be rejection is logged and instrumented. - Watch. Point your notification subscriber at a dashboard. Each entry is a real client that would have been rejected: fix the contract, or wait for that traffic to drain.
- Enforce. Flip to enforce, controller by controller. Every 422 you now return is one you already counted.
Then keep it that way: bin/rails "permittable:audit[strict]" crosses your contracts with the route set and exits 1 on any write action that accepts a body without a contract, which makes it a CI gate.
orders
POST /orders create enforce
PUT /orders/{id} update no contract — ACCEPTS A BODY
Details: monitor mode · generating drafts · auditing coverage.
Documentation
The guide is the full manual.
- Complete example: every option at once, in one events API
- Declaring contracts: field DSL · field options · types and strict coercion · defaults and partial updates · reusing fields · output reshaping
- Errors: custom messages and I18n · RFC 9457 problem+json · unknown parameters
- Safety: schema-drift guard · log redaction · instrumentation
- Beyond the controller: RSpec matchers · standalone contracts · OpenAPI export
- Reference: API · errors caught at class load
Compatibility
| Requirement | Supported |
|---|---|
| Ruby | >= 3.2 |
| Rails / ActiveSupport | >= 6.1, < 9 |
| Required dependency |
activesupport only |
| Optional |
actionpack (rendering, before_action), activerecord (drift guard) |
CI runs the full suite against ActiveSupport 6.1, 7.0, 7.1, 7.2, 8.0 and 8.1 on Ruby 3.2 through 4.0, and a separate job installs the built gem with nothing but activesupport. Why the floor is 6.1.
Development
bundle install
bundle exec rspec # the suite, with a coverage report in coverage/
bundle exec rubocop
bundle exec ruby benchmark/overhead.rb # a full contract vs. the params.permit call it replacesReleases are automated: bump lib/permittable/version.rb, add a CHANGELOG.md section, then push a vX.Y.Z tag. CI publishes to RubyGems via trusted publishing (OIDC — no API keys stored) and creates the GitHub release.
License
MIT.