Yesterday I was working on a new feature for a client when I ran into an issue. The ActiveRecord model I was working with had a number of constraints on the table that prevented me from creating a record. I removed the constraints from the table, as I decided that in this case they were unecessary. Unfortunately decisions like this aren't always as straight forward.

I tend to avoid using constraints when possible in my applications, especially when I am using Rails. I can rely on validations and associations to act as 'soft constraints' to my data and ensure that my data is valid. These are also backed up with tests for each model and its validations and associations to other models. This is by no means a perfect solution, but it has sufficed in the past.

Now, a lot of developers might think that constraints are not required as ActiveRecord provides all the necessary plumbing for validating and joining tables together with relationships. That's fair to say if your application is thoroughly tested and doesn't house critical information, but we all want to be good developers so really we should be using constraints where required.

In the past I've worked on a number of healthcare systems that required certain fields to be populated in specific tables. Domains that are directed by rules and regulations on what data you should persist are a great place to use database constraints. Enforcing the data integrity rules on your database reduces the risk for having missing information that could potentially land you in trouble. Domains such as healthcare, law and even education are all examples of domains where by database constraints could be needed.

Applications that also share their data are another good case for database constraints. While you do have validations and associations for your Rails application, can you make the same assumptions about other applications that can access your data? Using database constraints here can ensure that your data remains valid.

In Rails it's all too easy to assume your database is simply a place to hold data, but your database can provide extra validations and checks when needed. I tend to favour not using database constraints until a feature or bug requires that I absolutely need one in place. I find it's much easier to work with code that isn't restricted by countless constraints that have been placed on a table from the start merely because the developer at the time thought that field 'x' was a required field and should have a constraint on it.