3

Is there an easy (or generally accepted) way to load up a binary column using the create method of ActiveRecord?

For example, what I'm trying to do is something similar to this:

MyTableObject.create(name: 'Test', image: File.read('PathToMyFile.jpg'))
1
  • It doesn't seem to be ... unless I'm just doing it wrong. The create method returns true and I do see the record in the DB; however, the image isn't recoverable and the reported filesize doesn't match up. Commented Aug 27, 2009 at 20:51

2 Answers 2

4

I was able to get this working. Rather than doing:

MyTableObject.create(
    name: 'Test',
    image: File.read('PathToMyFile.jpg')
)

which did insert a record into the database but without the correct binary representation of the file

MyTableObject.create(
    name: 'Test',
    image: File.open('PathToMyFile.jpg', 'rb').read
)

seemed to do the trick.

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

2 Comments

Looks like a Windows-only problem - in Windows (but not unix-alikes like Linux or OSX) binary and text files are handled differently, hence the need for the explicit 'rb' mode param to correctly load the file.
Not a Windows-only problem. I had the same problem with a UNIX system (XUBUNTU, to be precise). And the recommended solution also worked on my system.
0

You can also use binread https://ruby-doc.org/core-3.1.2/IO.html#binread-method

MyTableObject.create(name: 'Test', image: File.binread('PathToMyFile.jpg'))

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.