Dmitry
Dmitry

Reputation: 7563

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?

Upvotes: 3

Views: 6960

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176562

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.

Upvotes: 15

Related Questions