views:

84

answers:

5

Is it generally better practice (and why) to validate attributes in the model or in the database definition?

For (a trivial) example:

In the user model:

validates_presence_of :name

versus in the migration:

t.string :name, :null => false 

On the one hand, including it in the database seems more of a guarantee against any type of bad data sneaking in. On the other hand, including it in the model makes things more transparent and easier to understand by grouping it in the code with the rest of the validations. I also considered doing both, but this seems both un-DRY and less maintainable.

+6  A: 

I would highly recommend doing it in both places. Doing it in the model saves you a database query (possibly across the network) that will essentially error out, and doing it in the database guarantees data consistency.

aseem
You beat me to it by 20 seconds ;)
Aurril
I agree with validating constraints in both places (I use PostgreSQL and the sexy_pg_constraints http://github.com/maxim/sexy_pg_constraints plugin for this) but it's not totally true that validating your in models will save a DB query. For example, `validates_uniqueness_of` has to do a DB query.
Luke Francl
+2  A: 

It is good practice to do both. Model Validation is user friendly while database validation adds a last resort component which hardens your code and reveals missing validitions in your application logic.

Aurril
+1  A: 

It varies. I think that simple, data-related validation (such as string lengths, field constraints, etc...) should be done in the database. Any validation that is following some business rules should be done in the model.

FrustratedWithFormsDesigner
A: 

Depends on your application design, If you have a small or medium size application you can either do it in both or just in model, But if you have a large application probably its service oriented or in layers then have basic validation i.e mandatory/nullable, min/max length etc in Database and more strict i.e patters or business rules in model.

Usman Akram
+2  A: 

And also

validates_presence_of :name

not the same to

t.string :name, :null => false 

If you just set NOT NULL column in your DB you still can insert blank value (""). If you're using model validates_presence_of - you can't.

uzzz
Good catch, thanks. Am I going blind, or is there really no prerolled validates_not_nil to put in the model logic to match up against database logic like everyone has recommended?
WIlliam Jones