On my user model I have a name and an email field and I want both to be unique.
I have read this https://github.com/hanami/validations#uniqueness-validation and while it makes perfect sense it still doesn’t help me implement this properly. I have unique index constraints on both fields but I can’t just show a stack trace, I need to render a nice message for the user.
I tried rescuing
Hanami::Model::UniqueConstraintViolationError and then adding the errors from there (similar to what was suggested in this old thread) but that error object has an empty interface so the only way I see of finding out which field had the unique constraint violated is by parsing the message, which seems like a strange thing to do for such a common thing.
Am I missing something? I would be very grateful if someone could share how they are handling uniqueness validations in their projects.
Hanami::Model::UniqueConstraintViolationError is a plain old
StandardError with a way more semantic name.
For now there’s no easy way to check which unique constraint failed, but we should add it (as it make sense). Could you. please, open an issue on
hanami/model for this?
I can open an issue, but if you already have an idea of how it should be implemented and you can point me in the right direction I’d be willing to just prepare a pull request.
The problem is that I trace the error all the way back to PG gem error and even on that I didn’t see a property for the column so I’m not sure how to get it other than parsing the error message but that sounds error prone since I have no idea how standard the message format is and if we can rely on it.
Have there been any changes about this? I’m new to Hanami and couldn’t figure out a better way to handle this besides rescuing
Hanami::Model::UniqueConstraintViolationError as mentioned here already. I couldn’t find much in the GitHub repo either.
AFAIK, nothing changed here. This was an issue on a pet project of mine so it wasn’t critical and I didn’t follow up.
However, my offer to implement a solution still stands as long as someone can point me in the right direction to save me research time.