I’m facing a trouble with my application: I have a constraint on my database where trip_id + trip_level_id must be unique.
Now, this is at database level (no validation), if I try to add an item with those fields already present in db, I receive a “constraintexception”.
The problem is:
- The constraintexception is only relative to SQlite3, while I require something for “all database”, expecially I’ll use mysql in production while sqlite3 in development.
- After the constraint exception, mongrel shutdown and this is definitely not what I want. I want to send the user a message “constraint exception happened” and just don’t add the item, the user need to go back and add an item that is correct.
How can I convert all those exception into errors that activerecords should fetch for me, if possible (this should be the greatest solution)?
Otherwise, how to declare a validation method that ensures that for those 2 columns, value should be unique?
Edit 1: I just noticed I can’t rescue SQLite3::ConstraintException on save method, at least not if I’m using just the Exception class. I think I must declare a validation, but it feels a bit redundant if already exists in database.
Edit 2: These seems to talk about the problem: https://rails.lighthouseapp.com/projects/8994/tickets/2419-raise-specific-exceptions-for-violated-database-constraints however it looks like they didn’t apply it, but the post is really old (3 years)
Reading around, I discovered that database constraints aren’t very well implemented in activerecord, and using a validates_uniqueness_of with a scope will solve my problem.
I definitely don’t like the solution for optimization, but I couldn’t find a way to effectively rescue the exception in my create and update methods, so actually I solved in this way.