From 1b0a353c4f192a59e08cf4e54534e6aa0d41a8c9 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 1 Nov 2019 21:02:14 -0500 Subject: [PATCH] Add Add A Check Constraint To A Table as a rails til --- README.md | 3 +- rails/add-a-check-constraint-to-a-table.md | 35 ++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 rails/add-a-check-constraint-to-a-table.md diff --git a/README.md b/README.md index 41a2745..0c585c7 100644 --- a/README.md +++ b/README.md @@ -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). -_860 TILs and counting..._ +_861 TILs and counting..._ --- @@ -487,6 +487,7 @@ _860 TILs and counting..._ ### 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 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) diff --git a/rails/add-a-check-constraint-to-a-table.md b/rails/add-a-check-constraint-to-a-table.md new file mode 100644 index 0000000..e67de9f --- /dev/null +++ b/rails/add-a-check-constraint-to-a-table.md @@ -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.