1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-06 08:38:01 +00:00

Add Allow Associations To Be Optional as a Rails TIL

This commit is contained in:
jbranchaud
2023-05-09 17:07:08 -05:00
parent 34b38244c4
commit 746957ca75
2 changed files with 37 additions and 1 deletions

View 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)