diff --git a/README.md b/README.md index 6da4c7f..189f097 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). -_863 TILs and counting..._ +_864 TILs and counting..._ --- @@ -500,6 +500,7 @@ _863 TILs and counting..._ - [Attribute Getter without the Recursion](rails/attribute-getter-without-the-recursion.md) - [Attribute Was](rails/attribute-was.md) - [Autosave False On ActiveRecord Associations](rails/autosave-false-on-activerecord-associations.md) +- [Build A Hash Of Model Attributes](rails/build-a-hash-of-model-attributes.md) - [Capybara Page Status Code](rails/capybara-page-status-code.md) - [Cast Common Boolean-Like Values To Booleans](rails/cast-common-boolean-like-values-to-booleans.md) - [Change The Nullability Of A Column](rails/change-the-nullability-of-a-column.md) diff --git a/rails/build-a-hash-of-model-attributes.md b/rails/build-a-hash-of-model-attributes.md new file mode 100644 index 0000000..12ace8c --- /dev/null +++ b/rails/build-a-hash-of-model-attributes.md @@ -0,0 +1,34 @@ +# Build A Hash Of Model Attributes + +Have you ever found yourself creating an `ActiveRecord` object with +[FactoryBot](https://github.com/thoughtbot/factory_bot) with the sole purpose +of turning it into a hash of attributes? + +```ruby +> FactoryBot.build(:book).attributes +{ "id"=>nil, "title"=>"Fledgling", "genre"=>"fiction" } +``` + +FactoryBot has a built-in method for doing this: + +```ruby +> FactoryBot.attributes_for(:book) +{ title: "Fledgling", genre: "fiction" } +``` + +It also accepts any traits for that factory: + +```ruby +> FactoryBot.attributes_for(:book, :published) +{ + title: "Fledgling", + genre: "fiction", + publication_year: 2005, + page_count: 362 +} +``` + +This is a handy way of build a base set of attributes when testing an API +endpoint. + +[source](https://devhints.io/factory_bot)