Understanding Rails · Season 4: Controllers, routing and auth
Strong parameters and params.expect
Episode 28 · deep dive · about 4 minutes · Rails 8.1 · by Tommy A. Caruso
How was this episode?
The series' author reads every note, and no one else sees it. When something is wrong or unclear, it gets fixed and the episode re-cut. How this series stays right.
Not endorsed yet. Are you a Rails developer? What's an endorsement?
Endorse this version To endorse: create an account, confirm your email, then link GitHub.
Why mass assignment is dangerous, and how expect shapes params.
Free to watch. If it helped, support the series.
Transcript
0:00 Strong parameters and params.expect
Episode twenty eight. Strong parameters, and params expect. Everything in a request comes from the person sending it, and they can send anything. Today: how Rails decides which of it reaches your models.
0:17 What a person can send
Here's what a person could send to create a note: a body and a notebook id, which the form has. But also a status of published, and a lock version. None of those last two are in the form. Anyone can add them, with the browser's tools or a single curl command.
0:34 Mass assignment
If Rails let you pass all of that straight into a model, it would save every key. That's mass assignment, and it's how users end up publishing what they shouldn't, or making themselves admins. So Rails refuses. Note dot new, with the raw params, raises forbidden attributes error.
0:53 params.expect
Calling params expect names what's allowed. A note, with a body and a notebook id. The result is permitted, and holds only those two. Status and lock version are dropped.
1:06 require and permit
Before Rails eight, you wrote require note, then permit. It filters the same way, and in development the log lists what it dropped: unpermitted parameters, status and lock version.
1:18 A string instead of a hash
The difference is the shape. Send note equals hello, a plain string instead of a hash. Require returns the string, and permit fails on it: undefined method permit for a string. The request ends as a five hundred, a server error, though the server did nothing wrong.
1:37 A 400, not a 500
Expect checks the shape first. Note must be a hash, so the same request raises parameter missing. Rails answers that with four hundred, bad request, which is the truth: the request was wrong. That's why the generators now write params expect.
1:54 Lists of values
Expect also shapes what's inside. Tag ids, with empty brackets, allows a list of plain values. Send a list, and it comes through. Send a single value where a list belongs, and it's dropped.
2:08 Nested hashes
A nested hash is a key with its own list. Cover, with color, allows the cover's color, and drops its price.
2:16 Lists of hashes
For a list of hashes, use double brackets. Notes, with body inside two pairs of brackets, allows many notes, each with only a body. The status on the second note is dropped. And a single hash where a list of them belongs is dropped too.
2:32 A single value
It works on single values too. And params expect id returns the id. Send an array where one id belongs, and it's a bad request, not a surprise deeper in your code.
2:44 expect!
There's also expect with a bang. It raises expected parameter missing, which Rails doesn't map to four hundred, so it's a five hundred. Use it where bad params mean a bug in your own code, like an internal API, not a person's typo.
3:01 Not authorization
One more thing strong parameters won't do. Permitting notebook id lets a person name any notebook, including one that isn't theirs. Which notebooks they may use is authorization, and that's episode thirty one.
3:16 The rules
So: never pass raw params to a model. Use params expect, in one private method per controller. Spell out the shape: brackets for lists, double brackets for lists of hashes. And check ownership separately.
3:30 Next
Next: sessions, cookies and the flash.
Check your understanding
-
What happens when a controller calls Note.new(params[:note]) with the raw params?
- Rails saves every key that was sent
- Rails raises ActiveModel::ForbiddenAttributesError
- Rails keeps only the columns notes has
Show answer
Rails raises ActiveModel::ForbiddenAttributesError. Parameters can't be used for mass assignment until they're permitted, so Rails refuses raw params. Source: Action Controller: strong parameters (Rails Guides 8.1).
-
Someone posts note=hello, a string where a hash belongs. What does params.expect(note: [:body]) lead to?
- A 500 server error
- A note with an empty body
- A 400 Bad Request
Show answer
A 400 Bad Request. expect checks the shape first and raises ParameterMissing, which Rails answers with 400. require(:note).permit(:body) would call permit on a string and end as a 500. Source: ActionDispatch::ExceptionWrapper (Rails source, v8.1.4.1).
-
Which expect call allows a notebook with many notes, each with only a body?
- params.expect(notebook: [:name, notes: [:body]])
- params.expect(notebook: [:name, notes: [[:body]]])
- params.expect(notebook: [:name, :notes])
Show answer
params.expect(notebook: [:name, notes: [[:body]]]). Double brackets ask for an array of hashes. Each hash keeps only the keys listed inside. Source: Action Controller: expect (Rails Guides 8.1).
-
When would you use params.expect! instead of params.expect?
- When missing params mean a bug in your own client code, so it should be a server error
- When a person might mistype a form field
- When you want a 400 response instead of a 500
Show answer
When missing params mean a bug in your own client code, so it should be a server error. expect! raises ExpectedParameterMissing, which isn't answered with 400. It surfaces as an error to fix, like a bug in an internal API client. Source: ActionController::Parameters#expect! (Rails API 8.1).
Sources
Every example in this episode was run on Rails 8.1.4.1 and Ruby 4.0.2.
- Action Controller: strong parameters (Rails Guides 8.1)
- Action Controller: expect (Rails Guides 8.1)
- Action Controller: nested parameters (Rails Guides 8.1)
- ActionController::Parameters#expect (Rails API 8.1)
- ActionController::Parameters#expect! (Rails API 8.1)
- ActionDispatch::ExceptionWrapper (Rails source, v8.1.4.1)