1

I want to ensure that a binary field has always value. I added a validation code like below.

class Foo < ActiveRecord::Base
  validates :b, presence: true
end

However, the change seems to cause the error.

$ rails c
> Foo.create(b:File.read('b.jpg'))

ArgumentError: invalid byte sequence in UTF-8

The error doesn't always appear. Only when the binary data has non-ascii codes.

How can I validate the binary field?

I made the environment like below. A image file(b.jpg, less than 16KB) is also 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

1 Answer 1

2

File.read returns a String that will claim to have UTF-8 encoding by default. That means that this:

Foo.create(b: File.read('b.jpg'))

is really:

some_utf8_string = File.read('b.jpg')
Foo.create(b: some_utf8_string)

But a JPEG will rarely be a valid UTF-8 string so you're going to get that ArgumentError whenever someone tries to treat it as UTF-8.

You can specify an encoding when you read your JPEG:

Foo.create(b: File.read('b.jpeg', encoding: 'binary'))

That should get past your encoding problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.