0

By SQL level validations, I meant the validations that we put in migrations like this:

add_column :leads, :count, null: false

By model-level validations, I meant the validations we put in models like this:

validates_presence_of :count

How are these two different? How is having both helpful? Is it enough that I only put model-level validations?

VoodooChild92
  • 1,993
  • 3
  • 19
  • 24
  • 1
    Did you check this out ? http://stackoverflow.com/questions/2367281/ruby-on-rails-is-it-better-to-validate-in-the-model-or-the-database. Quoting from the link "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." – Pramod Solanky Aug 27 '15 at 10:58

2 Answers2

2

SQL validations are performed on database level and not having them implemented in the model might lead into some exceptions raised from db layer (basically from mysql/pg/put-your-adapter gem).

Model level validations are performed before the query is run against database.

The best option is to have both. Even if something goes wrong with your model validation - it will be catched on database level. Good example here is unique constraint. If you have a huge load on the database you can encounter race condition problem and model validation is not enough here. Thanks to having unique constraint you can be sure that your data integrity is protected.

2

Model level validation helps you by providing user error messages when there is a validation error. and other helpers like valid? methods to check the object is ready to insert.

Mean while db level validations make sure your database sanity at DB layer.

That said you can always have more complex business logic based validations in model level may be by involving and transforming data in few other tables.