5

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.

0

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer! Haven't tried it but the gem looks very simple, effective and light on source code, converting schema.rb into validations, but not inspecting the database. Wouldn't quite have worked for my use case, sharing a DB with someone who kept changing the schema willy nilly, but might certainly use in future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.