fesplugas / database_constraints

Constraints for PostgreSQL the rails way.

This URL has Read+Write access

Joe Van Dyk (author)
Sat Oct 24 11:50:34 -0700 2009
fesplugas (committer)
Wed Oct 28 16:01:51 -0700 2009
commit  0c2ba465e7f11980f2a7294dd3112da057126dd6
tree    74022be63b0f050e302f9ab5805178e70db136f8
parent  6f4bd61dd0ca7bc75b125ec61b48681b170e518c
name age message
file MIT-LICENSE Loading commit data...
file README.rdoc
file Rakefile
directory generators/
file init.rb
directory lib/
directory test/
README.rdoc

Database Constraints

Adding database constraints to PostgreSQL the Rails way.

Available constraints:

  • Email: Validates format of email
  • Login: Validates uniqueness of login names
  • Positive: Validates positiveness of a number
  • Length: Validates length of a value
  • Uniqueness
  • Foreign keys

Example

Foreign keys:

    class AddForeignKeysToModels < ActiveRecord::Migration

      def self.up
        # add_foreign_key :from_table, :from_column, :to_table
        add_foreign_key :articles, :user_id, :users
      end

      def self.down
        # remove_foreign_key :from_table, :from_column
        remove_foreign_key :articles, :user_id
      end

    end

Validations:

    class AddConstraintsToModels < ActiveRecord::Migration

      def self.up
        add_email_check :users, :email
        add_login_check :users, :login
        add_positive_check :products, :price
        add_length_check :users, :login, :is => 8
        add_uniqueness_check :user, :login
      end

      def self.down
        remove_email_check :users, :email
        remove_login_check :users, :login
        remove_positive_check :users, :price
        remove_length_check :users, :login, :is => 8
        remove_uniqueness_check :user, :login
      end

    end

How to test?

Create a PostgreSQL database named database_constraints and run rake.

Copyright © 2008-2009 Francesc Esplugas Marti, released under the MIT license