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

Add Add A Check Constraint To A Table as a rails til

This commit is contained in:
jbranchaud
2019-11-01 21:02:14 -05:00
parent 8f248ac4d2
commit 1b0a353c4f
2 changed files with 37 additions and 1 deletions

View File

@@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
_860 TILs and counting..._ _861 TILs and counting..._
--- ---
@@ -487,6 +487,7 @@ _860 TILs and counting..._
### Rails ### Rails
- [Add A Check Constraint To A Table](rails/add-a-check-constraint-to-a-table.md)
- [Add A Foreign Key Reference To A Table](rails/add-a-foreign-key-reference-to-a-table.md) - [Add A Foreign Key Reference To A Table](rails/add-a-foreign-key-reference-to-a-table.md)
- [Add React With Webpacker To A New Rails App](rails/add-react-with-webpacker-to-a-new-rails-app.md) - [Add React With Webpacker To A New Rails App](rails/add-react-with-webpacker-to-a-new-rails-app.md)
- [Access Secrets In A Rails 5.2 App](rails/access-secrets-in-a-rails-5-2-app.md) - [Access Secrets In A Rails 5.2 App](rails/access-secrets-in-a-rails-5-2-app.md)

View File

@@ -0,0 +1,35 @@
# Add A Check Constraint To A Table
PostgreSQL allows you to enforce all kinds of rules about the value of a column
or the relationship between two columns. These rules are defined with [_check
constraints_](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-CHECK-CONSTRAINTS).
ActiveRecord's migration DSL does not provide a way for adding check
constraints directly. They can be added by executing a SQL statement in a
migration.
```ruby
class EnsurePageCountIsPositive < ActiveRecord::Migration[5.2]
def up
execute <<-SQL
alter table books
add constraint ensure_page_count_is_positive
check (page_count > 0);
SQL
end
def down
execute <<-SQL
alter table books
drop constraint ensure_page_count_is_positive;
SQL
end
```
This check constraint ensures that, anytime you add or update a row in the book
column, the value of `page_count` column is always greater than `0`. This is a
nice thing to enforce because it wouldn't make much sense for a book to have,
say, `-10` pages.
Note: these constraints will not appear in your `db/schema.rb` file. If you
want to see what check constraints have been defined across your tables, you
can crack open `psql` to investigate.