mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Allow Associations To Be Optional as a Rails TIL
This commit is contained in:
@@ -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)
|
||||
|
||||
35
rails/allow-associations-to-be-optional.md
Normal file
35
rails/allow-associations-to-be-optional.md
Normal file
@@ -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)
|
||||
Reference in New Issue
Block a user