Skip to content

Commit 09122d4

Browse files
committed
POST: Expecting Perfection from ActionController::Parameters
1 parent e2a87ce commit 09122d4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
---
2+
layout: post
3+
title: Expecting Perfection from ActionController::Parameters
4+
categories:
5+
- today-i-learned
6+
tags:
7+
- ruby on rails
8+
---
9+
10+
Today, I learned that Rails 8 introduced a new **ActionController::Parameters** method called `expect`. This allows for cleaner and safer parameter permission and requiring. I must have just missed this in the documentation, but what a nice quality-of-life feature to add.
11+
12+
<!--excerpt-->
13+
14+
**Before Rails 8**
15+
16+
Previously, you would have to require the top level key **:user** in this case and then permit its
17+
keys with a secondary method call.
18+
19+
```ruby
20+
params.require(:user).permit(:name)
21+
```
22+
23+
**After Rails 8**
24+
25+
With Rails 8+, you can now use a simpler syntax to achieve the same results.
26+
27+
> expect is the preferred way to require and permit parameters. It is safer than the previous recommendation to call permit and require in sequence, which could allow user triggered 500 errors.
28+
> expect is more strict with types to avoid a number of potential pitfalls that may be encountered with the .require.permit pattern.
29+
>
30+
> - [ActionController::Parameters#expect ](https://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-expect)
31+
32+
The above **require** to **permit** are now contained within a single method call with well-structured
33+
arguments.
34+
35+
```ruby
36+
params.expect(user: [:name])
37+
```

0 commit comments

Comments
 (0)