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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With