mysql - How to validate string attributes avoiding "ActiveRecord::StatementInvalid: Mysql2::Error: Data too long for column [...]" exception? -
i'm facing problem mysql text columns related string attributes containing utf-8 characters. let's suppose have migration one:
class createitems < activerecord::migration def change create :items |t| t.text "description", null: false end end end
as know maximum length of mysql
text
column 65535 bytes, , adding validation 1 below should prevent such mysql
exception:
class item < activerecord::base validates :description, length: { maximum: 65535 } end
and of course works moment when user puts long text containing characters more 1 byte long. how difference? see example:
> s = "a text national characters ĄąĘę" => "a text national characters ĄąĘę" > s.length => 41 > s.bytesize => 45
so e.g. if puts long description 65500 character long lots of such characters, validation passes mysql not forgive...
temporarily i've created bytesize
validation:
class bytesizevalidator < activemodel::eachvalidator def validate_each(record, attribute, value) record.errors.add(attribute, :too_long, count: options[:maximum]) if value.bytesize > options[:maximum] end end
which used in model follows:
validates :description, bytesize: { maximum: 65535 }
solves problem believe, there simple solution. maybe missed , possible make regular rails length validation
covering multibyte characters expected here?
i use rails 4.2.5.1, ruby 2.2.4 , mariadb 15.1 on linux.
Comments
Post a Comment