Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 376
William Jones Avatar asked Mar 02 '10 22:03

William Jones


People also ask

How does validate work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.

Does Rails need a database?

No, you don't need to use a db if you don't need it. However, keep in mind that Rails is vert tied with the idea of database and ActiveRecord. to require only the frameworks you need.

Does Ruby on Rails have a database?

Rails comes with built-in support for SQLite, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.


2 Answers

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.

like image 101
aseem Avatar answered Oct 11 '22 21:10

aseem


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.

like image 30
uzzz Avatar answered Oct 11 '22 21:10

uzzz