I would like to use ActiveRecord in my Rails application, but I would like to encode data constraints in the PostgreSQL database instead of in the ActiveRecord models.
For example, if I have a model generated by a scaffold,
rails generate scaffold User name:string email:string yearofbirth:integer
I'll want to make sure that the name is reasonably long. e.g.
class User < ActiveRecord::Base
validates :name, :length => { :maximum => 140 }
validates_uniqueness_of :name
validates_numericality_of :yearofbirth, :greater_than_or_equal_to => 1900
end
These validations are nice because ActiveRecord will throw up some nice error messages to the view if one tries to add in bad data.
However, I would like to encode the rules in the database itself, and have the database throw up the same nice looking and informative error messages to ActiveRecord, which will then pass them to the view layer. For example,
create table "Users" (
id integer unique,
name varchar(140) unique check(length(name)<140),
email varchar(255),
yearofbirth integer check (yearofbirth >= 1900)
);
What do I need to do in PostgreSQL or ActiveRecord to make this happen? When I tried it with the pgAdmin III tool, it threw up error messages, but I would like to customize them.
Also, is there a way to encode these database rules right into the database migration files in Ruby?
I appreciate any help you can give me.