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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With