diff --git a/README.md b/README.md index a4ed18d..a6461ac 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/rails/allow-list-params-anywhere-with-strong-params.md b/rails/allow-list-params-anywhere-with-strong-params.md new file mode 100644 index 0000000..96035e4 --- /dev/null +++ b/rails/allow-list-params-anywhere-with-strong-params.md @@ -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.