Reddirt
Reddirt

Reputation: 5953

Rails setting a maximum length on a string

The is the first time I've set a string length maximum in Rails.

It looks like I can add this to the workorder model:

validates_length_of :description, :maximum => 100

And I can create a migration with this:

change_column :workorders, :description, :string,  :limit => 100

Do I need both?

Upvotes: 2

Views: 2520

Answers (1)

Gray Kemmey
Gray Kemmey

Reputation: 1002

You should definitely include it in the migration, because this defines the actual structure of your database. This will also constrain the maximum storage size limit of the column (past a certain point, see http://dev.mysql.com/doc/refman/5.0/en/char.html for more details). Additionally, it's possible for more than just your Rails App to touch the database.

Including it in the validation is just good practice for robustness, though not strictly required.

Upvotes: 4

Related Questions