After a while of development your project, you might notice that you have some inconsistencies between your database constraints and validations. Right now, we will talk about two possible situations.
Imagine you defined your table as following:
create_table :users do |t|
And your model definition:
class User < ApplicationRecord validates :email, presence: true end In this case, the validation can be skipped by some methods and the null value will be inserted in the database. In most cases, you probably don't want this to happen so it's better to have not null constraint in the database. **Case #2**. Imagine you defined your table as following: create_table :users do |t| t.string :name, null: false end
And your model definition: class User < ApplicationRecord end
In this case, the **valid?**`` method will return **`true`** for the records which cannot be created. Moreover, the attempt to insert a row will execute from 1 up to a few SQL queries and in a result raise an error and rollback the whole transaction. Those all things are **very inefficient** and can be easily skipped by just adding presence validation. You should add it in most cases. So the question is how to find all possible issues automatically without manually checking all models? Here [database_consistency](https://github.com/djezzzl/database_consistency) gem comes in handy. Right now, it detects most of issues. Also, it helps us to detect the issue where a column has not-null constraint but there is possible `null` insert defined by the optional presence validator. *Try it yourself and share your feedback. Feel free to contribute! Any thoughts are welcome! P.S. This is my own topic was copy-pasted from [reddit](https://www.reddit.com/r/rails/comments/9x1lsd/consistency_between_database_constraints_and/) to spread the info about the gem. *