From 746957ca7569795cbebc0ff078e90d725594afe3 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 9 May 2023 17:07:08 -0500 Subject: [PATCH] Add Allow Associations To Be Optional as a Rails TIL --- README.md | 3 +- rails/allow-associations-to-be-optional.md | 35 ++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 rails/allow-associations-to-be-optional.md diff --git a/README.md b/README.md index 2a5cfa0..dde9cfe 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). -_1300 TILs and counting..._ +_1301 TILs and counting..._ --- @@ -763,6 +763,7 @@ _1300 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 Associations To Be Optional](rails/allow-associations-to-be-optional.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) - [Alphabetize Schema Columns To Keep Them Consistent](rails/alphabetize-schema-columns-to-keep-them-consistent.md) diff --git a/rails/allow-associations-to-be-optional.md b/rails/allow-associations-to-be-optional.md new file mode 100644 index 0000000..058709f --- /dev/null +++ b/rails/allow-associations-to-be-optional.md @@ -0,0 +1,35 @@ +# Allow Associations To Be Optional + +As of Rails 5, whenever a `belongs_to` association is declared in an +`ActiveRecord` model, it is assumed to be a required association. + +```ruby +class Book < ApplicationRecord + belongs_to :author +end +``` + +If we were to create a `Book` instance without an `Author`, then we would get +an error – `Validation Failed: Author is missing`. + +We could either make sure to always create books with authors or, if it makes +sense for our data model, we could treat the author as optional. + +The most explicit and precise way to make a relation optional is to declare it +as such in the `belongs_to` directive. + +```ruby +class Book < ApplicationRecord + belongs_to :author, optional: true +end +``` + +Another approach, though I don't recommend it unless you have a strong reason, +is to globally make associations optional. You can do this by adding the +following line to your `config/application.rb` file. + +```ruby +config.active_record.belongs_to_required_by_default = false +``` + +[source](https://www.bigbinary.com/blog/rails-5-makes-belong-to-association-required-by-default)