Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to set validations based on database constraints? #14

Open
nickjj opened this issue Jun 19, 2023 · 1 comment
Open

Is it possible to set validations based on database constraints? #14

nickjj opened this issue Jun 19, 2023 · 1 comment

Comments

@nickjj
Copy link

nickjj commented Jun 19, 2023

I'm a big fan of having my database be the source of truth which often means setting up DB constraints.

For example:

  add_check_constraint :users, "char_length(display_name) <= 70", name: "display_name_length"

Then my model would typically have a validation like this:

  validates :display_name, presence: true, length: { maximum: 70 }

You can have different types of constraints too such as:

  add_check_constraint :packages, "amount >= 0 AND amount <= 2147483647", name: "amount_range"

With a validation of:

  validates :amount, numericality: { only_integer: true, in: 0..2_147_483_647 }

You could also have:

  add_check_constraint :packages, "char_length(discount_amount_label) <= 18", name: "discount_amount_label_length"

With a validation of:

  validates :discount_amount_label, allow_nil: true, length: { maximum: 19 }

In the above example the column itself allows null values so this tool could extract that from the schema.

It would be tricky to pick out all of them with perfect accuracy since character lengths and things like ranges can have arbitrary expressions but maybe it's doable long term? I think capturing most of them with a reasonable amount of accuracy to get you going will be beneficial.

For example, check out this constraint:

   add_check_constraint :packages,
     "discount_amount >= 0 AND discount_amount <= 2147483647 AND discount_amount <= amount",
     name: "discount_amount_range"

And then its column information:

   t.integer :discount_amount, null: false, default: 0

If you wanted to programmatically create a validation from this you could factor:

  • It is of type integer so it must have whole numbers
  • It defaults to 0 and can't be null
  • It can't be larger than the amount

You could produce a validation like this:

  validates :discount_amount,
    numericality: { only_integer: true },
    comparison: { greater_than_or_equal_to: 0, less_than: :amount }

It may save some time of checking Rails' docs to put together that validation?

@hopsoft
Copy link
Owner

hopsoft commented Dec 30, 2023

Great ideas here. Happy to accept a PR that introduces some of this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants