Ruby on Rails: Is it better to validate in the model or the database? Ruby on Rails: Is it better to validate in the model or the database? database database

Ruby on Rails: Is it better to validate in the model or the database?


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.


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.


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.