# Using database for validation

**URL:** <https://www.ruby-forum.com/t/using-database-for-validation/113598>\
**Category:** Rails\
**Created:** [September 2, 2007, 4:10pm UTC](https://www.ruby-forum.com/t/using-database-for-validation/113598 "2007-09-02T16:10:10Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![dnstevenson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/8dc957/32.png) [@dnstevenson](https://www.ruby-forum.com/u/dnstevenson)\
**Post date:** [September 2, 2007, 4:10pm UTC](https://www.ruby-forum.com/t/using-database-for-validation/113598/1 "2007-09-02T16:10:10Z")

</div>

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.
