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
on 2007-07-14 08:39
on 2007-07-14 21:47
Look over: 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.