Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert database constraints to Rails validations

In a Rails app, the column names, types, and default values are inferred directly from the database. Is there any way of inferring validations from database constraints on initialization or while attempting to save?

This would allow more DRYness, and ensure that all data could be validated softly before hitting the DB and getting an exception, because the validations would cover all the database constraints. The database's constraints are the authoritative source of information on data invalidity when they are used.

Alternatively, is it possible to make ActiveRecord rescue from hitting a database constraint, and act as though a weak validation has failed? That would mean that database constraints could be manipulated externally without restarting or editing the Rails app, the performance would be improved because uniqueness validations would not require a separate query, and also that uniqueness validations would be immune to race conditions.

like image 837
user1158559 Avatar asked Oct 21 '22 04:10

user1158559


1 Answers

You can use the Enforce Schema Rules gem:

https://github.com/twinge/enforce_schema_rules

It validates your model against database rules you’ve already created in your schema.

Example:

class Person < ActiveRecord::Base
  enforce_schema_rules :except => :dhh
end
like image 107
Hopstream Avatar answered Oct 24 '22 13:10

Hopstream