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

1 Answer 1

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
2
  • Looks great! Just one quick question: What does the 'wb' argument mean? Would it still work if I just said 'w+' instead?
    – Neil
    Mar 2, 2016 at 14:03
  • You can find the different modes here: stackoverflow.com/questions/3682359/… I don't think you need the + in your use case.
    – Pascal
    Mar 3, 2016 at 7:22

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.