6 August 2009 · About 1 minute read

Rails: Validating Unique Attributes with acts_as_revisable

I’ve been using the acts_as_revisable plugin in my Rails apps to store a revision history of ActiveRecord models. The plugin automatically versions your models, and allows you to navigate revisions; branch and merge changes, and perform bulk changesets.

During some tests of my code, I found a conflict between the plugin and ActiveRecord.validates_uniqueness_of. It seems the conflict occurs because acts_as_revisable stores all revisions in the same database table. For example, when trying to save a record whose :name attribute should be unique, the validator will see all previous versions of the record with identical names, and prevent the save.

The fix I put in for this was to use the :scope to scope validates_uniqueness_of by the revisable_is_current attribute:

```rubyclass User < ActiveRecord::Base

validates_as_unique :username, :scope => :revisable_is_current

end```

Scoping the attribute causes the validator to only consider records whose :revisable_is_current attribute matches that of the record being edited. This works for my app, as only the current revision (User#revisable_is_current= true) will ever be edited.

Are you using acts_as_revisable and come across this problem? Spotted a better solution? Feel free to discuss ideas in the comments.

Chris Blunt
Chris Blunt @cblunt
Chris is the founder of Plymouth Software. As well as code and business, he enjoys being a Dad, swimming, and the fine art of drinking tea.