diff --git a/README.md b/README.md index a8fbd52..2a5cfa0 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1299 TILs and counting..._ +_1300 TILs and counting..._ --- @@ -832,6 +832,7 @@ _1299 TILs and counting..._ - [Migrating Up Down Up](rails/migrating-up-down-up.md) - [Order Matters For `rescue_from` Blocks](rails/order-matters-for-rescue-from-blocks.md) - [Params Includes Submission Button Info](rails/params-includes-submission-button-info.md) +- [Params Is A Hash With Indifferent Access](rails/params-is-a-hash-with-indifferent-access.md) - [Parse Query Params From A URL](rails/parse-query-params-from-a-url.md) - [Perform SQL Explain With ActiveRecord](rails/perform-sql-explain-with-activerecord.md) - [Polymorphic Path Helpers](rails/polymorphic-path-helpers.md) diff --git a/rails/params-is-a-hash-with-indifferent-access.md b/rails/params-is-a-hash-with-indifferent-access.md new file mode 100644 index 0000000..1efac71 --- /dev/null +++ b/rails/params-is-a-hash-with-indifferent-access.md @@ -0,0 +1,32 @@ +# Params Is A Hash With Indifferent Access + +When you have an instance of `ActionController::Parameters`—which you often do +with `params` in a Rails controller—under the hood you have a +`HashWithIndifferentAccess`. + +Here is what the initializer looks like when you call +`ActionController::Parameters.new(some_hash)`. + +```ruby +def initialize(parameters = {}, logging_context = {}) + @parameters = parameters.with_indifferent_access + @logging_context = logging_context + @permitted = self.class.permit_all_parameters +end +``` + +This means you can reference the keys in your parameters as either a _string_ +key or a _symbol_ key. + +```ruby +> params = ActionController::Parameters.new({ username: 'tacocat' }) +=> #"tacocat"} permitted: false> +> params['username'] +=> "tacocat" +> params[:username] +=> "tacocat" +``` + +Note that `ActiveSupport::HashWithIndifferentAccess` is not an ancestor of the +`ActionController::Parameters` class (like it once used to be), but is just how +the incoming hash is transformed when initialized.