In the database, the Foreign Key constraint enforces referential integrity.
This ensures the parent record has to be present before creating a child record
and these constraints are immediately enforced(checked after each statement).
But, this behavior can be changed within a transaction by changing a constraints deferrable
characteristics,
which means instead of checking the constraints immediately, these checks will be deferred until the transaction is committed
and PostgreSQL supports this feature in which constraints can be deferred
So, before Rails 7, we had to write a raw SQL in migrations to use the deferrable
constraints in Postgres.
Before
It will result in the below error
After
But, in Rails 7, while passing the :deferrable
option to the add_foreign_key
statement in migrations,
it is possible to defer this check.
We can specify whether
or not the foreign key should be deferrable.
Valid values are booleans or :deferred
or :immediate
.
deferrable: false
:- Default value, constraint check is always immediate.deferrable: true
:- Doesn’t change the default behavior, but allows manually deferring the check within a transaction.deferrable: :deferred
:- Constraint check will be done once the transaction is committed and allows the constraint behavior to change within transaction.deferrable: :immediate
:- Constraint check is immediate and allows the constraint behavior to change within transaction.
Records will be created successfully
Check out this pull request to know about the change.