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:

- 2,159
- 13
- 25
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.
Some databases (such as Postgres) allow you to place constraints on the columns to enforce the buisness logic on the database layer but thats a very different story. Constraints are mostly useful if you need to prevent invalid data from being inserted if validations are bypassed or for avoiding potential race conditions.
In most cases an application (Rails) level validation will be sufficient. And constraints must be complemented with application layer validations anyways.
See:

- 96,212
- 14
- 104
- 165
...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,948
- 3
- 31
- 45
-
One thing to keep in mind is that if you decide to use a constraint like this you need to switch from Ruby to SQL schema dumps or your constraints will be "lost in translation" when dumping the schema or when recreating the DB from the schema. https://stackoverflow.com/questions/34394823/what-is-the-difference-between-rails-structure-sql-and-schema-rb – max Feb 02 '23 at 10:23
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.

- 108
- 2
- 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