5

I want to save an image as a base64 string as part of a model in Rails.

Does anyone have advice for the migration file?
I assume that simply setting a type of String would not be suitable, given that the size of the string is often large e.g. > 2MB.

amaseuk
  • 2,147
  • 4
  • 24
  • 43

1 Answers1

7

You could use either text or binary instead of string in your migration if you want to overcome the size limitation.

http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column

The API documentation gives this example:

td.column(:picture, :binary, :limit => 2.megabytes)
# => picture BLOB(2097152)

The maximum size of TEXT or BLOB (binary) columns depends on your RDBMS (e.g. MySQL, PostgreSQL), available memory, and certain configuration settings. For instance, in MySQL, you should have a look at the max_allowed_packet option, which you can set to anything up to 1 GB.

Regarding storage with Paperclip:

Paperclip doesn't allow database storage out of the box, so you have to write some custom code for that. Google gives me this:

http://patshaughnessy.net/2009/5/29/paperclip-sample-app-part-3-saving-file-attachments-in-a-database-blob-column

It's outdated though, so I'm not sure if it's helpful.

More importantly:

Note that storing files in database is generally not recommended which is why Paperclip doesn't support it. Some reasons it's a bad idea:

  1. When images are stored in DB, every image request requires a call to your Rails app and the database, which has a massive negative effect on performance. If you store images as files or on Amazon S3, your app will scale much better.

  2. Your database becomes large very quickly, which makes it harder to backup your data.

  3. Since different RDBMS have different rules for column size, column types, etc., migrating large columns to a different database (e.g. from MySQL to PostgreSQL) may involve difficulties.

So I hope you have a good reason to do it anyway.

M. Cypher
  • 6,966
  • 2
  • 34
  • 34
  • The maximum size of a string or bytea type in postgresql is 2Gigs, but the OP is having up to 2M. So he's got lots of head room there. – Scott Marlowe Aug 14 '11 at 06:34
  • any idea how I could then save the binary as an image e.g. through paperclip ? – amaseuk Aug 15 '11 at 14:31
  • Sorry what I mean is that I am receiving base64 format and need to convert to image but I have found solution now: see http://stackoverflow.com/questions/4641728/base64-photo-and-paperclip-rails/4652604#comment-8459269 – amaseuk Aug 15 '11 at 20:20