Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, DRY default validator for string length?

So I am having an issue where length errors are rails exception because the model doesn't have a length validation on it.

I understand I can put a length validator on my string by using

validates :blah, length: { maximum: 255 }

However most of my strings are using the default size of 255, so I would have to repeat this validation in a lot of places.

Is there a DRY way to put a default validator on all strings to validate to the default database length of 255?

like image 559
James McMahon Avatar asked Feb 15 '23 12:02

James McMahon


1 Answers

The gem schema_validations (https://github.com/SchemaPlus/schema_validations) does what you want.

Automatically creates validations basing on the database schema.

It inspect the database and automatically creates validations basing on the schema. After installing it your model is as simple as it can be.

class User < ActiveRecord::Base
end

Validations are there but they are created by schema_validations under the hood.

like image 134
Grilse Avatar answered Feb 17 '23 21:02

Grilse