Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

rein

> 后端框架
Open source

Database constraints made easy for ActiveRecord.

669 stars0 likes1 views
WebsiteGitHub

About

Database constraints made easy for ActiveRecord.

Rein

Data integrity is a good thing. Constraining the values allowed by your application at the database-level, rather than at the application-level, is a more robust way of ensuring your data stays sane.

Unfortunately, ActiveRecord doesn't encourage (or even allow) you to use database integrity without resorting to hand-crafted SQL. Rein (pronounced "rain") adds a handful of methods to your ActiveRecord migrations so that you can easily tame the data in your database.

All methods in the DSL are automatically reversible, so you can take advantage of reversible Rails migrations.

Table of Contents

  • Getting Started
  • Constraint Types
    • Summary
    • Foreign Key Constraints
    • Unique Constraints
    • Exclusion Constraints
    • Inclusion Constraints
    • Length Constraints
    • Match Constraints
    • Numericality Constraints
    • Presence Constraints
    • Null Constraints
    • Check Constraints
    • Validate Constraints
  • Data Types
    • Enumerated Types
  • Views
  • Schemas
  • Examples
  • Contribute
  • License

Getting Started

Install the gem:

> gem install rein

Add a constraint to your migrations:

ruby
class CreateAuthorsTable < ActiveRecord::Migration
  def change
    create_table :authors do |t|
      t.string :name, null: false
    end

    # An author must have a name.
    add_presence_constraint :authors, :name
  end
end

Constraint Types

Summary

The table below summarises the constraint operations provided by Rein and whether they support validation.

Rein name Rein method SQL Supports NOT VALID?
Foreign Key add_foreign_key_constraint FOREIGN KEY yes
Unique add_unique_constraint UNIQUE no
Exclusion add_exclusion_constraint EXCLUDE no
Inclusion add_inclusion_constraint CHECK yes
Length add_length_constraint CHECK yes
Match add_match_constraint CHECK yes
Numericality add_numericality_constraint CHECK yes
Presence add_presence_constraint CHECK yes
Null add_null_constraint CHECK yes
Check add_check_constraint CHECK yes

Foreign Key Constraints

A foreign key constraint specifies that the values in a column must match the values appearing in some row of another table.

For example, let's say that we want to constrain the author_id column in the books table to one of the id values in the authors table:

ruby
add_foreign_key_constraint :books, :authors

Adding a foreign key doesn't automatically create an index on the referenced column. Having an index will generally speed up any joins you perform on the foreign key. To create an index you can specify the index option:

ruby
add_foreign_key_constraint :books, :authors, index: true

Rein will automatically infer the column names for the tables, but if we need to be explicit we can using the referenced and referencing options:

ruby
add_foreign_key_constraint :books, :authors, referencing: :author_id, referenced: :id

We can also specify the behaviour when one of the referenced rows is updated or deleted:

ruby
add_foreign_key_constraint :books, :authors, on_delete: :cascade, on_update: :cascade

Here's all the options for specifying the delete/update behaviour:

  • no_action: if any referencing rows still exist when the constraint is checked, an error is raised; this is the default behavior if you do not specify anything.
  • cascade: when a referenced row is deleted, row(s) referencing it should be automatically deleted as well.
  • set_null: sets the referencing columns to be nulls when the referenced row is deleted.
  • set_default: sets the referencing columns to its default values when the referenced row is deleted.
  • restrict: prevents deletion of a referenced row.

To remove a foreign key constraint:

ruby
remove_foreign_key_constraint :books, :authors

Unique Constraints

A unique constraint specifies that certain columns in a table must be unique.

For example, all the books should have unique ISBNs:

ruby
add_unique_constraint :books, :isbn

By default, the database checks unique constraints immediately (i.e. as soon as a record is created or updated). If a record with a duplicate value exists, then the database will raise an error.

Sometimes it is necessary to wait until the end of a transaction to do the checking (e.g. maybe you want to swap the ISBNs for two books). To do so, you need to tell the database to defer checking the constraint until the end of the current transaction:

sql
BEGIN;
SET CONSTRAINTS books_isbn_unique DEFERRED;
UPDATE books SET isbn = 'foo' WHERE id = 1;
UPDATE books SET isbn = 'bar' WHERE id = 2;
COMMIT;

This blog post offers a good explanation of how to do this in a Rails app when using the acts_as_list plugin.

If you always want to defer checking a unique constraint, then you can set the deferred option to true:

ruby
add_unique_constraint :books, :isbn, deferred: true

If you really don't want the ability to optionally defer a unique constraint in a transaction, then you can set the deferrable option to false:

ruby
add_unique_constraint :authors, :name, deferrable: false

Exclusion Constraints

An exclusion constraint is a lot like a unique constraint, but more general. Whereas a unique constraint forbids two rows from having all constrained columns be equal, an exclusion constraint forbids two rows from having all constrained columns be some relationship, where the relationship is up to you (and can be different for each column). For instance you can prevent two ranges from overlapping with the && operator. You can read more in the Postgres docs or a slideshow by the author, Jeff Davis.

For example, no two people should own copyright to a book at the same time:

ruby
add_exclusion_constraint :book_owners, [[:book_id, '='], [:owned_during, '&&']], using: :gist

By default, the database checks exclusion constraints immediately (i.e. as soon as a record is created or updated). If a record with an excluded value exists, then the database will raise an error.

Sometimes it is necessary to wait until the end of a transaction to do the checking (e.g. maybe you want to move the date a copyright changed hands). To do so, you need to tell the database to defer checking the constraint until the end of the current transaction:

sql
BEGIN;
SET CONSTRAINTS book_owners_exclude DEFERRED;
UPDATE book_owners
  SET owned_during = tsrange(lower(owned_during), '1943-12-22')
  WHERE book_id = 1 AND owner_id = 1;
UPDATE book_owners
  SET owned_during = tsrange('1943-12-22', upper(owned_during))
  WHERE book_id = 1 AND owner_id = 2;
COMMIT;

If you always want to defer checking a unique constraint, then you can set the deferred option to true:

ruby
add_exclusion_constraint :book_owners, [[:book_id, '='], [:owned_during, '&&']], using: :gist, deferred: true

If you really don't want the ability to optionally defer a unique constraint in a transaction, then you can set the deferrable option to false:

ruby
add_exclusion_constraint :book_owners, [[:book_id, '='], [:owned_during, '&&']], using: :gist, deferrable: false

If you want to specify something like a operator class for a attribute specific attribute, you can add it to the attribute specification between attribute name and the operator:

ruby
add_exclusion_constraint :book_owners, [[:book_id, :gist_int8_ops, '='], [:owned_during, '&&']], using: :gist

If you want to set the constraint to a subset of the table, you can use a where option to set the filter condition:

ruby
add_exclusion_constraint :books, [[:isbn, '=']], using: :gist, where: "state='active'"

Inclusion Constraints

An inclusion constraint specifies the possible values that a column value can take.

For example, we can ensure that state column values can only ever be available or on_loan:

ruby
add_inclusion_constraint :books, :state, in: %w[available on_loan]

To remove an inclusion constraint:

ruby
remove_inclusion_constraint :books, :state

You may also include an if option to enforce the constraint only under certain conditions, like so:

ruby
add_inclusion_constraint :books, :state,
  in: %w[available on_loan],
  if: "deleted_at IS NULL"

You may optionally provide a name option to customize the name:

ruby
add_inclusion_constraint :books, :state,
  in: %w[available on_loan],
  name: "books_state_is_valid"

Length Constraints

A length constraint specifies the range of values that the length of a string column value can take.

For example, we can ensure that the call_number can only ever be a value between 1 and 255:

ruby
add_length_constraint :books, :call_number,
  greater_than_or_equal_to: 1,
  less_than_or_equal_to: 255

Here's all the options for constraining the values:

  • equal_to
  • not_equal_to
  • less_than
  • less_than_or_equal_to
  • greater_than
  • greater_than_or_equal_to

You may also include an if option to enforce the constraint only under certain conditions, like so:

ruby
add_length_constraint :books, :call_number,
  greater_than_or_equal_to: 1,
  less_than_or_equal_to: 12,
  if: "status = 'published'"

You may optionally provide a name option to customize the name:

ruby
add_length_constraint :books, :call_number,
  greater_than_or_equal_to: 1,
  less_than_or_equal_to: 12,
  name: "books_call_number_is_valid"

To remove a length constraint:

ruby
remove_length_constraint :books, :call_number

Match Constraints

A match constraint ensures that a string column value matches (or does not match) a POSIX-style regular expression.

For example, we can ensure that the title can only contain printable ASCII characters, but not ampersands:

ruby
add_match_constraint :books, :title, accepts: '\A[ -~]*\Z', rejects: '&'

Match constraints are case-sensitive. You make them case-insensitive by using accepts_case_insensitive and rejects_case_insensitive instead of accepts or rejects.

If you only want to enforce the constraint under certain conditions, you can pass an optional if option:

ruby
add_match_constraint :books, :title, accepts: '\A[ -~]*\Z', if: "status = 'published'"

You may optionally provide a name option to customize the name:

ruby
add_match_constraint :books, :title, name: "books_title_is_valid"

To remove a match constraint:

ruby
remove_match_constraint :books, :title

Numericality Constraints

A numericality constraint specifies the range of values that a numeric column value can take.

For example, we can ensure that the publication_month can only ever be a value between 1 and 12:

ruby
add_numericality_constraint :books, :publication_month,
  greater_than_or_equal_to: 1,
  less_than_or_equal_to: 12

Here's all the options for constraining the values:

  • equal_to
  • not_equal_to
  • less_than
  • less_than_or_equal_to
  • greater_than
  • greater_than_or_equal_to

You may also include an if option to enforce the constraint only under certain conditions, like so:

ruby
add

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyactiverecordconstraintsdatabaselibrary

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架