DEV Community

Samuel Lubliner
Samuel Lubliner

Posted on ā€¢ Edited on

1

Data integrity with validations

Here I addresses the issue of data integrity and validation in a Ruby on Rails application. Prevent invalid data from getting saved into the database, and reducing the need for defensive coding.

Invalid Records

Invalid records could can come from due user input, CSV imports, API calls, etc.

Defensive Code

Defensive coding gets inefficient.

Data Integrity with Validations

ActiveRecord enforces data integrity by providing validations. They prevent the .save method from executing if the record is invalid, returning false instead of true.

Common Validators

  • Presence: ensures a value is present before saving.
  • Uniqueness: ensures that the value is unique across the table.

Conclusion

ActiveRecord validations efficiently enforce data integrity at the model level. This reduces the need for defensive code in the views or controllers. Instead of fixing data-related issues at the view level, enforce correct data at the model level. This makes the application more robust and maintainable. Official Rails Guide on validations.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more