Skip to content

Commit 7b376de

Browse files
authored
Merge pull request rails#48026 from alpaca-tc/postgresql-unique-constraints-guides
Add a section on unique constraints to the AR PostgreSQL guide
2 parents c396f20 + 5adc11c commit 7b376de

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

guides/source/active_record_postgresql.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ After reading this guide, you will know:
1010
* How to use PostgreSQL's datatypes.
1111
* How to use UUID primary keys.
1212
* How to use deferrable foreign keys.
13+
* How to use unique constraints.
1314
* How to implement full text search with PostgreSQL.
1415
* How to back your Active Record models with database views.
1516

@@ -600,6 +601,27 @@ end
600601

601602
By default `:deferrable` is `false` and the constraint is always checked immediately.
602603

604+
Unique Constraint
605+
-----------------
606+
607+
* [unique constraints](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-UNIQUE-CONSTRAINTS)
608+
609+
```ruby
610+
# db/migrate/20230422225213_create_items.rb
611+
create_table :items do |t|
612+
t.integer :position, null: false
613+
t.unique_key [:position], deferrable: :immediate
614+
end
615+
```
616+
617+
If you want to change an existing unique index to deferrable, you can use `:using_index` to create deferrable unique constraints.
618+
619+
```ruby
620+
add_unique_key :items, deferrable: :deferred, using_index: "index_items_on_position"
621+
```
622+
623+
Like foreign keys, unique constraints can be deferred by setting `:deferrable` to either `:immediate` or `:deferred`. By default, `:deferrable` is `false` and the constraint is always checked immediately.
624+
603625
Full Text Search
604626
----------------
605627

0 commit comments

Comments
 (0)