0

In the database I have the table users. This table has the column mugshot which is of type mediumblob. I know that this mediumblob's content type is image/jpeg.

What I want to do is write a ruby script that requires in ActiveRecord, and does the following:

  • iterate through all the records within the users table
  • Create a .jpg file from the data within that mediumblob field
  • name the file according to other columns on the users table. Example: "#{user.first_name}_#{user.last_name}.jpg".

The part I am having trouble figuring out is how to rip out the image from that mediumblob field and then name the file what I want:

User.all.each do |user|
 # rip out the image from the mediumblob field
 # save the file as "#{user.first_name}_#{userlast_name}.jpg"
 # save the file within the folder 'my_images' located on the Desktop
end
Neil
  • 4,578
  • 14
  • 70
  • 155

1 Answers1

1

Have you tried something like:

User.find_each do |user|
  File.open("#{user.first_name}_#{user.last_name}.jpg", 'wb') do |file|
    file << user.mugshot
  end
end
Pascal
  • 8,464
  • 1
  • 20
  • 31
  • Looks great! Just one quick question: What does the 'wb' argument mean? Would it still work if I just said 'w+' instead? – Neil Mar 02 '16 at 14:03
  • You can find the different modes here: http://stackoverflow.com/questions/3682359/what-are-the-ruby-file-open-modes-and-options I don't think you need the ```+``` in your use case. – Pascal Mar 03 '16 at 07:22