mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
Add Allow List Params Anywhere With Strong Params as a rails til
This commit is contained in:
@@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
|
||||
|
||||
_934 TILs and counting..._
|
||||
_935 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -550,6 +550,7 @@ _934 TILs and counting..._
|
||||
- [Access Secrets In A Rails 5.2 App](rails/access-secrets-in-a-rails-5-2-app.md)
|
||||
- [ActiveRecord Query For This Or That](rails/active-record-query-for-this-or-that.md)
|
||||
- [Advance The Date](rails/advance-the-date.md)
|
||||
- [Allow List Params Anywhere With Strong Params](rails/allow-list-params-anywhere-with-strong-params.md)
|
||||
- [All or Nothing Database Transactions](rails/all-or-nothing-database-transactions.md)
|
||||
- [Assert Two Arrays Have The Same Items With RSpec](rails/assert-two-arrays-have-the-same-items-with-rspec.md)
|
||||
- [Attach A File With Capybara](rails/attach-a-file-with-capybara.md)
|
||||
|
||||
33
rails/allow-list-params-anywhere-with-strong-params.md
Normal file
33
rails/allow-list-params-anywhere-with-strong-params.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# Allow List Params Anywhere With Strong Params
|
||||
|
||||
The intended use of
|
||||
[`StrongParams`](https://api.rubyonrails.org/classes/ActionController/StrongParameters.html)
|
||||
is to prevent unintended params from getting through a controller action during
|
||||
mass assignment.
|
||||
|
||||
This can be put to use other places in your Rails app, such as a service
|
||||
object, where mass assignment is used to update records.
|
||||
|
||||
```ruby
|
||||
class BookTitleUpdater
|
||||
ALLOW_LIST = [:title].freeze
|
||||
|
||||
def self.run(data)
|
||||
params = ActionController::Parameters.new(data).permit(*ALLOW_LIST)
|
||||
|
||||
Book.find(params[:id]).update!(params)
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
This helps prevent other values from getting inadvertently updated on the `book` record.
|
||||
|
||||
```ruby
|
||||
> ALLOW_LIST = [:title]
|
||||
> data = { title: "Legacy Code", author_id: 22 }
|
||||
> params = ActionController::Parameters.new(data).permit(*ALLOW_LIST)
|
||||
> params.to_h
|
||||
#=> { title: "Legacy Code" }
|
||||
```
|
||||
|
||||
The `author_id` value is ignored and won't be passed to the `#update` call.
|
||||
Reference in New Issue
Block a user