SchemaValidations is an ActiveRecord extension that keeps your model class definitions simpler and more DRY, by automatically defining validations based on the database schema.
One of the great things about Rails (ActiveRecord, in particular) is that it inspects the database and automatically defines accessors for all your columns, keeping your model class definitions simple and DRY. That's great for simple data columns, but where it falls down is when your table contains constraints.
create_table :users do |t|
t.string :email, null: false, limit: 30
t.boolean :confirmed, null: false
end
In that case the constraints null: false
, limit: 30
and :boolean
must be validated on the model level, to avoid ugly database exceptions:
class User < ActiveRecord::Base
validates :email, presence: true, length: { maximum: 30 }
validates :confirmed, presence: true, inclusion: { in: [true, false] }
end
...which isn't the most DRY approach.
SchemaValidations aims to DRY up your models, doing that boring work for you. It inspects the database and automatically creates validations based on the schema. After installing it your model is as simple as it can be.
class User < ActiveRecord::Base
end
Validations are there but they are created by schema_validations under the hood.
Simply add schema_validations to your Gemfile.
gem "schema_validations"
Constraints:
Constraint | Validation |
---|---|
null: false |
validates ... presence: true |
limit: 100 |
validates ... length: { maximum: 100 } |
unique: true |
validates ... uniqueness: true |
unique: true, case_sensitive: false (If schema_plus_pg_indexes is also in use) |
validates ... uniqueness: { case_sensitive: false } |
Data types:
Type | Validation |
---|---|
:boolean |
:validates ... inclusion: { in: [true, false] } |
:float |
:validates ... numericality: true |
:integer |
:validates ... numericality: { only_integer: true, greater_than_or_equal_to: ..., less_than: ... } |
:decimal, precision: ... |
:validates ... numericality: { greater_than: ..., less_than: ... } |
SchemaValidations' behavior can be configured globally and per-model.
In an initializer, such as config/initializers/schema_validations.rb
, you can set any of these options. The default values are shown.
SchemaValidations.setup do |config|
# Whether to automatically create validations based on database constraints.
# (Can be set false globally to disable the gem by default, and set true per-model to enable.)
config.auto_create = true
# Restricts the set of field names to include in automatic validation.
# Value is a single name, an array of names, or nil.
config.only = nil
# Restricts the set of validation types to include in automatic validation.
# Value is a single type, an array of types, or nil.
# A type is specified as, e.g., `:validates_presence_of` or simply `:presence`.
config.only_type = nil
# A list of field names to exclude from automatic validation.
# Value is a single name, an array of names, or nil.
# (Providing a value per-model will completely replace a globally-configured list)
config.except = nil
# A list of validation types to exclude from automatic validation.
# Value is a single type, an array of types, or nil.
# (Providing a value per-model will completely replace a globally-configured list)
config.except_type = nil
# The base set of field names to always exclude from automatic validation.
# Value is a single name, an array of names, or nil.
# (This whitelist applies after all other considerations, global or per-model)
config.whitelist = [:created_at, :updated_at, :created_on, :updated_on]
# The base set of validation types to always exclude from automatic validation.
# Value is a single type, an array of types, or nil.
# (This whitelist applies after all other considerations, global or per-model)
config.whitelist_type = nil
end
You can override the global configuration per-model, using the schema_validations
class method. All global configuration options are available as keyword options. For example:
class User < ActiveRecord::Base
schema_validations auto_create: false
end
class User < ActiveRecord::Base
schema_validations except: :email # don't create default validation for email
validates :email, presence: true, length: { in: 5..30 }
end
class User < ActiveRecord::Base
schema_validations whitelist: nil
end
If you're curious (or dubious) about what validations SchemaValidations defines, you can check the log file. For every assocation that SchemaValidations defines, it generates a debug entry in the log such as
[schema_validations] Article.validates_length_of :title, :allow_nil=>true, :maximum=>50
which shows the exact validation definition call.
SchemaValidations defines the validations lazily for each class, only creating them when they are needed (in order to validate a record of the class, or in response to introspection on the class). So you may need to search through the log file for "schema_validations" to find all the validations, and some classes' validations may not be defined at all if they were never needed for the logged use case.
As of version 1.2.0, SchemaValidations supports and is tested on:
Earlier versions of SchemaValidations supported:
null: false
with a
default defined (#18, #49):money
type:decimal
when precision
is nil (#37):decimal
range validation. Thanks to @felixbuenemannThis major version is backwards compatible for most uses. Only those who specified a per-model :except
clause would be affected.
:except
per-model would clobber the default values. E.g. using the documented example except: :mail
would accidentally cause validations to be issued updated_at
to be validated. Now :except
works more naturally. This is however technically a breaking change, hence the version bump.SchemaValidations is derived from the "Red Hill On Rails" plugin schema_validations originally created by harukizaemon (https://github.com/harukizaemon)
SchemaValidations was created in 2011 by Michał Łomnicki and Ronen Barzel
Are you interested in contributing to schema_validations? Thanks! Please follow the standard protocol: fork, feature branch, develop, push, and issue pull request.
Some things to know about to help you develop and test:
schema_dev: SchemaValidations uses schema_dev to facilitate running rspec tests on the matrix of ruby, activerecord, and database versions that the gem supports, both locally and on github actions
To to run rspec locally on the full matrix, do:
$ schema_dev bundle install
$ schema_dev rspec
You can also run on just one configuration at a time; For info, see schema_dev --help
or the schema_dev README.
The matrix of configurations is specified in schema_dev.yml
in
the project root.
Code coverage results will be in coverage/index.html -- it should be at 100% coverage.
This gem is released under the MIT license.