4

Rails migrations allow you to specify a max length for a string column with the limit attribute. Is there a corresponding attribute for minimum length or can it only be done through validations on the model?

jfredson
  • 141
  • 11

4 Answers4

1

No, there is no corresponding min_length declaration. The best solution is validations at the model level. You can see the available options here:

https://github.com/rails/rails/blob/acbcec8ea869849f98213fea5e554bb3a82fea61/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb#L55

Anthony L
  • 1,995
  • 11
  • 24
0

The max length is a database feature which controls how much memory the DB allocates for the column. This is very different compared to a validation as the DB just truncates anything beyond that length.

There is no corresponding minimum on any db that I know of. Nor would it be a particularly useful feature IMHO. So it should be handled by an application (Rails) level validation not the database schema definition.

See:

max
  • 87,587
  • 14
  • 97
  • 154
0

...can it only be done through validations on the model?

Probably, not exactly what you are looking for but if you use Postgresql, you can use CONSTRAINT:

ALTER TABLE table_name
  ADD CONSTRAINT check_minimum_length CHECK (LENGTH(column_name) >= 5);

Still, I would highly recommend using ActiveModel::Validations as validations should be done at application layer.

ogirginc
  • 4,326
  • 3
  • 26
  • 41
-2

Yes, it's posible. Like Rails Guides show, you should use in the model:

validates :column_name, length: { minimum: 2 }

Visit the link for more validation types.

Necrogoru
  • 92
  • 1
  • 9