William Jones
William Jones

Reputation: 18279

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

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.

Upvotes: 44

Views: 8516

Answers (6)

Valera Prokopchuk
Valera Prokopchuk

Reputation: 126

I would recommend Migration Validators project ( https://rubygems.org/gems/mv-core ) to define validation on db level and then transparently promote it to ActiveRecord model.

Example:

in migration:

def change
  create_table :posts do |t|
    t.string :title, length: 1..30
  end 
end

in your model:

class Post < ActiveRecord::Base
  enforce_migration_validations
end

As result you will have two level data validation. The first one will be implemented in db ( as condition in trigger of check constraint ) and the second one as ActiveModel validation in your model.

Upvotes: 1

uzzz
uzzz

Reputation: 559

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.

Upvotes: 15

Usman Akram
Usman Akram

Reputation: 271

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.

Upvotes: 0

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.

Upvotes: 2

Aurril
Aurril

Reputation: 2469

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.

Upvotes: 5

aseem
aseem

Reputation: 820

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.

Upvotes: 55

Related Questions