Using database for validation

I’ve been playing around with the idea of using the database for model
validation where possible (instead of duplicating that validation in
rails). My first approach to this was to catch exceptions from save/
create and parse the errors, in my case from postgres, to turn them
into something friendlier. Something like:

def update
create
end

def create
begin
super
rescue ActiveRecord::StatementInvalid => e
errors.add_to_base(e.to_s)
end
end

but apparently rails ignores errors at this point. This just results
in rails thinking the record is saved when it has not been. So next I
tried something more elaborate. This is a bit contrived and I don’t
think I would actually use this but I’m just trying to figure out
callbacks and such:

def initialize (attrs = nil)
super(attrs)
@attempt = 0
end

def update
create
end

def create
begin
@attempt += 1
if @attempt == 1
@error = nil
super
end
rescue ActiveRecord::StatementInvalid => e
@error = e.to_s
end
end

def after_save
if !@error.nil? and @attempt < 2
save!
end
end

def validate
if @error.nil?
super
else
errors.add_to_base(@error)
end
end

The idea was to catch the original exception and save it, force it
back thru “save” and set the error in that second passes call to
validate. Even though the call to “errors.add_to_base(@error)” works,
it doesn’t seem to prevent the exception being thrown in the UI.

Has anyone attempted something like this or have any ideas how to
proceed? I guess I’m gonna have to dig into the rails code a bit
deeper.