DRYing up your validations using DB reflection

Out of the box, ActiveRecord will silently truncate attribute values which exceed their column width.

This is potentially surprising to users. To improve usability, we can set a validation:

Now we have a new problem: duplication of the length cap. The number “10” now appears in both the database migrations, and the model validations.

We could extract it out into a constant, although referencing models can be problematic in migrations. But that still doesn’t account for the (many) cases where we don’t specify an explicit field limit in the migration, and instead rely on the built-in ActiveRecord defaults for field limits.

Here’s a solution that uses database reflection to validate a field is within its DB column size limit:

ActiveRecord provides the columns_hash to get at column metadata gathered from the database backend. In the code above we query it for the limit attribute, and use that as the max field length. By pulling the limit from the DB, we avoid duplication of knowledge.