No commit activity in last 3 years
No release in over 3 years
Keep your code DRY by inferring column validations from table properties! Automagically validate presence, length, numericality, and inclusion of ActiveRecord backed columns.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
 Dependencies

Development

Runtime

>= 3.1.0
 Project Readme

Validates By Schema (validates_by_schema)

Build Status Code Climate Dependency Status Gem Version

Automatic validation based on your database schema column types and limits. Keep your code DRY by inferring column validations from table properties!

Example

Say you had a table setup like this:

create_table "widgets", :force => true do |t|
  t.integer  "quantity", :limit => 2
  t.decimal  "thickness", :precision => 4, :scale => 4
  t.string   "color", :null => false
end

Then these validations are inferred when you add validates_by_schema to your model:

validates :quantity, numericality: { allow_nil: true,
  greater_than: -32768, less_than: 32768}
validates :thickness, numericality: {allow_nil: true,
  less_than_or_equal_to: 0.999, greater_than_or_equal_to: -0.999}
validates :color, presence: true, length: {allow_nil: false, maximum: 255}

Installation

  1. Add it to your Gemfile:
gem "validates_by_schema"
  1. Then bundle

  2. Call it from your ActiveRecord model:

class Widget < ActiveRecord::Base
  validates_by_schema
end

Usage

You can also whitelist or blacklist columns with :only or :except options, respectively:

validates_by_schema only: [:body, :description]
validates_by_schema except: [:name, :title]

The primary key and timestamp columns are not validated.

Notes

Column properties are inferred by your database adapter (like pg, mysql2, sqlite3), and does not depend on migration files or schema.rb. As such, you could use this on projects where the database where Rails is not in control of the database configuration.

This has been tested with mysql, postgresql, and sqlite3. It should work with any other database that has reliable adapter.