I entered 5kb text in string field(VARCHAR(255)) and received this error:
Mysql2::Error: Data too long for column 'title' at row 1: INSERT INTO `posts`....
What is the best way to fix this problem?
Should i cut this text to 255 in before_save in model?
Or fix params[:that_field] in controller?
Any other solutions?
The solution depends on what you want to achieve. It’s all about user experience.
If you want users to be able to enter data longer than 255 characters for this field, then change the field from
:stringto:text.If you don’t want the data to be longer than 255, then you have two options. If you want to be able to provide a validation message to the user, then add a validation to your
Postmodel.Third option, if you don’t mind about the message, use a callback (for example a
:before_save) to trim the value before writing it to the database. You can also override the default setter for the attribute if you prefer the string to be truncated just after being set.