Forum: Ruby on Rails [Rails][Newb] How Rescue DB constraint violation?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
584a6682a2defd3bc5f7dc85fd6e263d?d=identicon&s=25 Bjorn Boulder (bornboulder)
on 2007-07-14 08:39
(Received via mailing list)
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
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

Ef0db53920b243d6758c2f6b1306df0d?d=identicon&s=25 Steve Ross (cwd)
on 2007-07-14 21:47
(Received via mailing list)
Look over:

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.
This topic is locked and can not be replied to.