mysql - How to validate a binary field using Ruby on Rails? -
i want ensure binary field has value. added validation code below.
class foo < activerecord::base validates :b, presence: true end however, change seems cause error.
$ rails c > foo.create(b:file.read('b.jpg')) argumenterror: invalid byte sequence in utf-8 the error doesn't appear. when binary data has non-ascii codes.
how can validate binary field?
i made environment below. image file(b.jpg, less 16kb) needed.
$ rails --version rails 4.2.0 $ rails new test_binary --database=mysql $ cd test_binary/ $ rails g model foo b:binary $ rake db:create db:migrate
file.read returns string claim have utf-8 encoding default. means this:
foo.create(b:file.read('b.jpg')) is really:
some_utf8_string = file.read('b.jpg') foo.create(b: some_utf8_string) but jpeg valid utf-8 string you're going argumenterror whenever tries treat utf-8.
you can specify encoding when read jpeg:
foo.create(b: file.read('b.jpeg', encoding: 'binary')) that should past encoding problem.
Comments
Post a Comment