4
votes

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?

3
Would it help to have a way to have validates assume a length: { maximum: 255 } default?Peter Alfvin
If so, see answer just posted. :-)Peter Alfvin

3 Answers

2
votes

This probably isn't exactly the answer you are looking for but if you add multiple fields to the validator then you aren't really repeating the validator and seems fairly DRY to me.

validates :foo, :bar, :baz, length: { maximum: 255 }
6
votes

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.

0
votes
class ModelName < ActiveRecord::Base
  validates :name, length: { maximum: 255 }
end

Then use it by typing

ModelName.validators