# \[Rails\]\[Newb\] How Rescue DB constraint violation?

**URL:** <https://www.ruby-forum.com/t/rails-newb-how-rescue-db-constraint-violation/109398>\
**Category:** Rails\
**Created:** [July 14, 2007, 8:39am UTC](https://www.ruby-forum.com/t/rails-newb-how-rescue-db-constraint-violation/109398 "2007-07-14T08:39:36Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bornboulder](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/e274bd/32.png) [@bornboulder](https://www.ruby-forum.com/u/bornboulder)\
**Post date:** [July 14, 2007, 8:39am UTC](https://www.ruby-forum.com/t/rails-newb-how-rescue-db-constraint-violation/109398/1 "2007-07-14T08:39:36Z")

</div>

Hello People,

I’m looking for a short demo of rescuing a DB constraint violation.

This is a newby question; my ruby skills are weak.

validation in the model is cool but I want to have the safety-net of  
DB constraints  
on top of validation.

I ran a little experiment to see what Rails does when a DB blocks  
attempted  
DML to prevent a contstraint violation.

The browser shows a 500 Error.

The development log shows this:

Symbl Create (0.000000) PGError: ERROR: duplicate key violates unique  
constraint “symbl\_name\_unique”  
: INSERT INTO symbls (“name”, “cname”) VALUES(‘ORCL’, ‘oracle2’)  
SQL (0.000378) ROLLBACK

ActiveRecord::StatementInvalid (PGError: ERROR: duplicate key  
violates unique constraint “symbl\_name\_unique”

Does anyone have a short demo of rescuing a DB constraint violation?

I’d like to send a friendly message to the end-user rather than a 500  
error.

-b

---

<div class="post-metadata">

**Author:** ![bornboulder](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/e274bd/32.png) [@bornboulder](https://www.ruby-forum.com/u/bornboulder)\
**Post date:** [July 14, 2007, 9:47pm UTC](https://www.ruby-forum.com/t/rails-newb-how-rescue-db-constraint-violation/109398/2 "2007-07-14T21:47:27Z")

</div>

Look over:

[http://whytheluckystiff.net/ruby/pickaxe/](http://whytheluckystiff.net/ruby/pickaxe/)

Then, wrap your database access in a begin/rescue block. Note that  
ActiveRecord implicitly wraps database accesses in a transaction that  
is rolled back on exception. The primary time you will use  
transactions is when more than one table must be updated to preserve  
relational integrity.

Hope this gets you started along the right path.
