Skip to content

Commit bd8acb7

Browse files
committedJul 10, 2020
Add Allow List Params Anywhere With Strong Params as a rails til
1 parent 9adbbd8 commit bd8acb7

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed
 

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
99

1010
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1111

12-
_934 TILs and counting..._
12+
_935 TILs and counting..._
1313

1414
---
1515

@@ -550,6 +550,7 @@ _934 TILs and counting..._
550550
- [Access Secrets In A Rails 5.2 App](rails/access-secrets-in-a-rails-5-2-app.md)
551551
- [ActiveRecord Query For This Or That](rails/active-record-query-for-this-or-that.md)
552552
- [Advance The Date](rails/advance-the-date.md)
553+
- [Allow List Params Anywhere With Strong Params](rails/allow-list-params-anywhere-with-strong-params.md)
553554
- [All or Nothing Database Transactions](rails/all-or-nothing-database-transactions.md)
554555
- [Assert Two Arrays Have The Same Items With RSpec](rails/assert-two-arrays-have-the-same-items-with-rspec.md)
555556
- [Attach A File With Capybara](rails/attach-a-file-with-capybara.md)
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Allow List Params Anywhere With Strong Params
2+
3+
The intended use of
4+
[`StrongParams`](https://api.rubyonrails.org/classes/ActionController/StrongParameters.html)
5+
is to prevent unintended params from getting through a controller action during
6+
mass assignment.
7+
8+
This can be put to use other places in your Rails app, such as a service
9+
object, where mass assignment is used to update records.
10+
11+
```ruby
12+
class BookTitleUpdater
13+
ALLOW_LIST = [:title].freeze
14+
15+
def self.run(data)
16+
params = ActionController::Parameters.new(data).permit(*ALLOW_LIST)
17+
18+
Book.find(params[:id]).update!(params)
19+
end
20+
end
21+
```
22+
23+
This helps prevent other values from getting inadvertently updated on the `book` record.
24+
25+
```ruby
26+
> ALLOW_LIST = [:title]
27+
> data = { title: "Legacy Code", author_id: 22 }
28+
> params = ActionController::Parameters.new(data).permit(*ALLOW_LIST)
29+
> params.to_h
30+
#=> { title: "Legacy Code" }
31+
```
32+
33+
The `author_id` value is ignored and won't be passed to the `#update` call.

0 commit comments

Comments
 (0)