Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Data too long for column

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?

like image 767
Dmitry Avatar asked Nov 25 '25 21:11

Dmitry


1 Answers

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 to :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 Post model.

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

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.

like image 167
Simone Carletti Avatar answered Nov 27 '25 12:11

Simone Carletti