Reputation: 49639
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?
Upvotes: 4
Views: 2182
Reputation: 3917
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.
Upvotes: 6
Reputation:
class ModelName < ActiveRecord::Base
validates :name, length: { maximum: 255 }
end
Then use it by typing
ModelName.validators
Upvotes: 0
Reputation: 852
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 }
Upvotes: 2