4

I am using Ruby, or more specifically the Ramaze framework with the Sequel ORM. So please don't tell me about the Paperclip gem, as it is only compatible with ActiveRecord.

With that in mind, how can I store an image in a database using Ruby and Sequel?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
desbest
  • 4,746
  • 11
  • 51
  • 84

1 Answers1

11
require "sequel"

DB = Sequel.sqlite

DB.create_table :images do
  primary_key :id
  String :name
  File :data
end

images = DB[:images]
images.insert(name: 'foo', data: Sequel.blob(File.read('/mydir/myimage.jpg')))
Mori
  • 27,279
  • 10
  • 68
  • 73
  • In most cases, you'll want to use `data: Sequel.blob(File.read('/mydir/myimage.jpg'))`. Maybe it doesn't matter on SQLite, but it will on other databases. – Jeremy Evans Jun 22 '14 at 16:56
  • The `Sequel.blob` does also matter with SQLite. I just received a `SQLite3::SQLException: unrecognized token`-error when I used `File.read` without `Sequel.blob` (it depends on the file content. Some files worked, other files dumped). – knut Jan 19 '16 at 09:41