Jean Mertz posted a nice writeup a while back on how to do uniqueness validations in ActiveModel. The gist of it is that since an ActiveModel object could map to any number of ActiveRecord classes, he subclassed ActiveRecord::Validations::UniquenessValidator to allow client code to specify the class in the validation declaration:
One small update to his code - using Rails 5.1.2, it seems ActiveRecord's runtime behavior has changed and so you need to override the constructor, not the setup method. So just:
And in order to work with composite unique constraints we need to factor in the scope variable name, so this needs to happen just before the super call:
Also, I wanted to call this out clearly as a custom validation, so I named the class ActiveModelUniquenessValidator and then declared the validation like this:
This is a nice tweak that can help clean up some custom validations. Good stuff, thanks Jean!