DEV Community

Augusts Bautra
Augusts Bautra

Posted on

TIL: DB constraints for column values in Rails

Today I used the opportunity to try out Rails' #add_check_constraint migration helper to constrain a new coefficient column's permitted values to only positive ones.

It's really simple!

add_check_constraint :my_things, "some_coefficient > 0",
  name: "my_things_some_coefficient_positive",
  if_not_exists: true
Enter fullscreen mode Exit fullscreen mode

This technique will help improve the data consistency and quality in the Rails app I maintain, alongside such long-standing techniques as disallowing NULLs, limiting length, and adding foreign-key constraints.

Top comments (0)