skip to content

In Rails 8, why does params.expect replace params.require(...).permit(...), and how does each handle a tampered job_application parameter?

level: middleimportance: must knowfreq 66%

answer

  1. new in Rails 8.0
  2. string instead of hash: NoMethodError
  3. expect: ParameterMissing, then 400
  4. only root keys are required
  5. expect! is not rescued

basics

~20 s

params.expect requires and permits in one type-strict call: a job_application sent as a string or the wrong shape raises ParameterMissing, answered 400, while require(...).permit(...) can crash with NoMethodError (500) or accept a hash where an array was meant.

solid answer

~40 s

With `params.require(:job_application).permit(...)`, a tampered request such as `job_application=hack` makes `require` return the string, and calling `permit` on it raises `NoMethodError` — a 500 and an error-tracker alert caused by the client. `permit` also treats `references: [:name]` as "a hash or an array of hashes", so the shape is not enforced. `params.expect(job_application: [...])`, added in **Rails 8.0** and generated by the 8.1 scaffold, permits first and then requires the root keys, with **explicit arrays**: an array of hashes must be written `[[...]]`. A root key that is missing, blank or the wrong type raises `ActionController::ParameterMissing`, which Rails maps to **400 Bad Request**. A nested value of the wrong shape is simply dropped. `expect!` raises `ExpectedParameterMissing`, which is deliberately left unmapped, so it surfaces as a 500.

code

ruby · 8 lines
ruby
params = ActionController::Parameters.new(job_application: "hack")

params.require(:job_application).permit(:full_name)
# => NoMethodError: undefined method 'permit' for an instance of String  (500)

params.expect(job_application: [ :full_name ])
# => ActionController::ParameterMissing: param is missing or the value is
#    empty or invalid: job_application  (400)

go deeper

for a junior

Write params.expect(model: [...]) and params.expect(:id) the way the Rails 8 scaffold does, and know that a bad root key returns 400.

for a middle

Contrast the two idioms: require on a string crashes permit, permit accepts a hash or an array, and expect permits first, requires root keys, and enforces explicit arrays.

for a senior

Plan the migration of older controllers, convert array filters to double brackets, test the 400 paths, and reserve expect! for internal clients where a 500 is the right alarm.

for a principal

Decide how strictly the app treats malformed client input across public and internal APIs, and which failures should page someone versus return a quiet 400.

## The pattern Rails 8 replaced For a decade the idiom was `params.require(:job_application).permit(:full_name, :email, references: [:name])`. It reads well, but it was written for well-behaved clients: - **`require` returns whatever is under the key.** If a client sends `job_application=hack`, the result is the string `"hack"`, and `.permit` on a string raises `NoMethodError`. The client caused a **500**, which pages someone. - **`permit` is relaxed about shape.** A filter like `references: [:name]` accepts either one hash or an array of hashes, so code written for an array can receive a single hash instead. - **The two calls can be written in the wrong order or split apart**, leaving required-but-unpermitted values in circulation. ## What params.expect does `expect` performs both steps in one call, in the safe order: 1. **Permit** with explicit array handling, building a new permitted object from the filters. 2. **Require** every root key named in the filters on that permitted result. 3. **Return** the single value, or an array of values when several root keys were named. Because the require step runs on the already-filtered result, a root key whose value does not match the declared shape counts as missing. | Call | Returns | |---|---| | `params.expect(:id)` | the scalar `id`, or raises if it is a hash, an array or blank | | `params.expect(job_application: [:full_name, :email])` | a permitted `Parameters` with those keys | | `params.expect(:page, job_application: [:full_name])` | an array: `[page, job_application_params]` | ## Tampered input, side by side | Request | `require(...).permit(...)` | `expect(...)` | |---|---|---| | `job_application=hack` | `NoMethodError`, 500 | `ParameterMissing`, 400 | | `job_application` missing | `ParameterMissing`, 400 | `ParameterMissing`, 400 | | `references` sent as one hash, declared as an array | accepted | dropped from the result | `ActionController::ParameterMissing` is in Action Dispatch's `rescue_responses` as `:bad_request`, so the client gets **400** without any code in the controller. Its message — `param is missing or the value is empty or invalid: job_application` — also suggests corrections for a mistyped key. ## Only root keys are required `expect` requires the **top-level** keys it names. Nested filters still filter: if `references_attributes` arrives as a string where `[[...]]` was declared, the nested key is left out of the result rather than raising. Validations on the model are still where "this field must be present" belongs. ## expect! for internal clients `params.expect!` behaves the same but raises **`ActionController::ExpectedParameterMissing`**, a subclass of `ParameterMissing`. Action Dispatch maps exceptions to statuses by exact class name, so the subclass is not mapped and surfaces as a **500** with a full report. The documented use is an internal API, where a malformed request means a bug in a client library that someone should fix, not a user to be told "bad request". ## Testing the 400 path Because `ParameterMissing` is mapped centrally, a controller does not need a `rescue_from` for it, but the behaviour is still worth a request test: 1. Post the form normally and assert the record is created. 2. Post `job_application=hack` as a plain string and assert `:bad_request`. 3. Post with the root key missing entirely and assert `:bad_request` again. In development, `consider_all_requests_local` shows the exception page with the 400 status; in production the generated `public/400.html` is served. Either way the client sees a client error instead of the server error the old idiom produced, which keeps error trackers quiet about requests that were simply malformed. A short way to put it in an interview: `require.permit` trusted the client's shape, `expect` checks it. Everything else — the 400 instead of the 500, the double brackets, the array return for several keys — follows from that one change. ## Migrating existing controllers - Generators already emit `expect` in Rails 8, including `params.expect(:id)` in `set_*` loaders. - rubocop-rails ships a `Rails/StrongParametersExpect` cop for Rails 8.0 and later; it is pending by default and its autocorrect is marked unsafe, because a shape that `permit` tolerated may now be rejected. - Arrays of hashes need the double brackets when converted: `references: [:name]` becomes `references: [[:name]]`. - `require` and `permit` remain available and are not deprecated; `expect` is the recommended form.

  • When would you choose params.expect! over params.expect in a Rails controller?
    For an internal API whose only clients are your own code. `expect!` raises `ExpectedParameterMissing`, which Action Dispatch does not map to 400, so a malformed request becomes a 500 with a full error report — the signal you want when it means a client library has a bug. Public endpoints should use `expect` and answer 400.
  • In Rails, what does params.expect(:page, job_application: [:full_name]) return?
    An array of the required values in the order the keys were given: the `page` scalar first, then the permitted `job_application` parameters. Destructure it with `page, attrs = params.expect(...)`. A single root key returns the value itself rather than a one-element array.
  • Does Rails' params.expect raise when a nested value has the wrong shape?
    No. Only the root keys named in the call are required. A nested key whose value does not match its declaration — a hash where `[[...]]` was declared, or an array where a scalar was expected — is left out of the permitted result, and the request continues without it.

  • params.expect is just an alias for require followed by permit.
  • A tampered root parameter makes params.expect raise NoMethodError, a 500.
  • params.expect raises for every nested key that has the wrong shape.
  • ExpectedParameterMissing is mapped to 400 because it subclasses ParameterMissing.
  • params.require(...).permit(...) was removed in Rails 8.

Assumes Rails 8.1.4; params.expect and expect! arrived in Rails 8.0, and the 8.1 scaffold generator emits params.expect(:id) and params.expect(model: [...]).