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?
-
1Possible duplicate of https://stackoverflow.com/questions/32156650/minimum-length-constraint-on-a-column – MrYoshiji Mar 02 '18 at 21:15
-
why not use validations? – khiav reoy Mar 03 '18 at 03:42
4 Answers
No, there is no corresponding min_length declaration. The best solution is validations at the model level. You can see the available options here:
- 1,995
- 11
- 24
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:
- 87,587
- 14
- 97
- 154
...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.
- 4,326
- 3
- 26
- 41
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.
- 92
- 1
- 9
-
1This is not what the questioner asked, he asked if it can be done in any way _other_ than validations. – John Hayes-Reed Mar 03 '18 at 01:02