Using Rails 3 validations and/or callbacks, what would be the cleanest way to ensure that only one record of a model has a boolean value ticked as true? I’d like to mark one record as the currently active model.
(I know another option is to use a has-one association, but I’m curious to know how to store this more directly in the model records.)
If all you want to do is validate it you can use
Just drop that in your model class. That will validate that the model has only one boolean_attribute set to true.
Note that you will have to work around the atomicity of swapping the boolean_attribute from one instance to another.
Depending on what database you are using you might be able to resolve it using a transaction. If your database doesn’t support transactions you might have to figure out a better way to guarantee data consistency (such us having a dedicated model that points to the “active” model and removing
boolean_attributealtogether, or replacingboolean_attributewith an integer that can be atomically incremented (highest number representing the active one).