Is setting the default values a best practices?

should I always set default values for e.g integer in migration?

...
add :count, :int, default: 0
...

You should use a default if it makes sense for the field. For example if a field is nullable, then maybe you can leave out the default and it will be null.

Or let’s say you have an appointments table and you have a “start_time” field that contains when the appointment starts. What would be a sensible default for this? Well, the DB cannot know when the appointment should start so you can’t set a default. So you would usually want a non-nullable field with no default. Then if you try to insert a row without a “start_time” value, your code will crash and show you that you have made an error.

3 Likes