This Gem helps to transfer the defaults from the database schema to the rails validations. To do this, it uses the information in schema.rb and transfers it to a concern file. This file should be included in the version control.
Add this line to your application's Gemfile:
gem 'generated_schema_validations'
And then execute:
$ bundle install
Or install it yourself as:
$ gem install generated_schema_validations
To generate app/models/concerns/schema_validations.rb
:
$ rails db:migrate
Add to app/models/application_record.rb
:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
include SchemaValidations # to include auto generated validations
end
Use it in a model after you defined the associations and enums:
class User < ApplicationRecord
belongs_to :client
belongs_to :other
enum :actived, no: 0, yes: 1
validate :email_address, email_format: true
schema_validations # to use auto generated validations
def stuff; end
end
Add to simplecov config file (e.g. .simplecov
):
add_filter '/app/models/concerns/schema_validations.rb'
Add to rubocop config file (e. g. config/rubocop.rb
):
AllCops:
Exclude:
- app/models/concerns/schema_validations.rb
Every time you change schema.rb file with rake tasks db:schema:dump
the generated file schema_validations.rb
will fresh created. The task db:migrate
use intern db:schema:dump
.
It is hardcoded, that this will only run on development environment.
t.text :stuff, null: false
# results in
validate :stuff, presence: true
t.string :stuff, limit: 10
# results in
validate :stuff, length: { maximum: 10 }
t.integer :stuff
# results in
validate :stuff, numericality: true
You can watch changes on schema_validations.rb
to understand the generated validations.
- Add exclusion for enum fields
- Check usage of schema_validations (see #3)
- Force excluding unique validations with where clause (see #2)
- Add
jsonb
andxml
as possible field type
- Enable rails 7.0 usage
- Close tempfile before reading
- Add validations of date and datetime columns to be in database range
- Exclude columns in unique validations
- Add column type
binary
Bug reports and pull requests are welcome on GitHub at https://github.com/Lichtbit/generated_schema_validations.
The gem is available as open source under the terms of the MIT License.