Rieles: datos demasiado largos para la columna

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`....

¿Cuál es la mejor forma de solucionar este problema?
Should i cut this text to 255 in before_save in model?
Or fix params[:that_field] in controller?
¿Alguna otra solución?

preguntado el 30 de junio de 12 a las 19:06

1 Respuestas

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 :string a :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 validación para usted Post modelo.

class Model < ...
  validates_length_of :title, :maximum => 255

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.

Respondido el 30 de junio de 12 a las 19:06

If I want to use 2nd solution, I need to redisplay form to user with errors with until @object.save render 'new'? - Dmitry

A systematic answer; rare animal. Thank you. - jejeje

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.