Skip to content
This repository has been archived by the owner on Jan 24, 2023. It is now read-only.

Garaio-REM/validates_lengths_from_database

 
 

Repository files navigation

<img src=“https://secure.travis-ci.org/rubiety/validates_lengths_from_database.png?branch=master” alt=“Build Status” />

Validates Lengths from Database

Few people add length validations to fields in their database, and when saving such fields that have exhausted their length, an SQL error occurs. This gem introspects your table schema for maximum lengths on string and text fields and automatically adds length validations to the model.

Installation

Include the gem using bundler in your Gemfile:

gem "validates_lengths_from_database"

Usage

In your model you can activate validations:

class Post < ActiveRecord::Base
  validates_lengths_from_database
end

It also supports filter-style :only and :except options:

class Post < ActiveRecord::Base
  validates_lengths_from_database :only => [:title, :contents]
end

class Post < ActiveRecord::Base
  validates_lengths_from_database :except => [:other_field]
end

If you’d rather specify the limits explicitly instead of pulling them from the database, you can set it:

class Post < ActiveRecord::Base
  validates_lengths_from_database :limit => 255
end

Or to set the limit differently for string (VARCHAR) and (TEXT) columns:

class Post < ActiveRecord::Base
  validates_lengths_from_database :limit => {:string => 255, :text => 4092}
end

Note that unfortunately this cannot be done at a global level directly against ActiveRecord::Base, since the validates_length_from_database method requires the class to have a table name (with the ability to load the schema).

Running Tests

# Just the gems locked in Gemfile.lock
$ bundle exec rake test

# All of the Appraisals:
$ bundle exec rake all

About

Introspects your database string field maximum lengths and automatically defines length validations.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Ruby 100.0%