【问题标题】:ActiveRecord: Rip out and name an image from a mediumblob in the databaseActiveRecord:从数据库中的 mediumblob 中提取并命名图像
【发布时间】:2016-03-02 05:36:35
【问题描述】:

在数据库中我有表users。此表具有 mugshot 列,其类型为 mediumblob。我知道这个 mediumblob 的内容类型是image/jpeg

我想做的是在 ActiveRecord 中编写一个 ruby​​ 脚本,并执行以下操作:

  • 遍历users 表中的所有记录
  • 根据该 mediumblob 字段中的数据创建一个.jpg 文件
  • 根据users 表中的其他列命名文件。示例:“#{user.first_name}_#{user.last_name}.jpg”。

我无法弄清楚的部分是如何从 mediumblob 字段中提取图像,然后将文件命名为我想要的名称:

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

【问题讨论】:

    标签: mysql ruby activerecord


    【解决方案1】:

    您是否尝试过类似的方法:

    User.find_each do |user|
      File.open("#{user.first_name}_#{user.last_name}.jpg", 'wb') do |file|
        file << user.mugshot
      end
    end
    

    【讨论】:

    • 看起来很棒!一个简单的问题:'wb' 参数是什么意思?如果我只是说“w+”,它仍然有效吗?
    • 您可以在这里找到不同的模式:stackoverflow.com/questions/3682359/… 我认为您的用例中不需要+
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2011-07-28
    • 1970-01-01
    • 2013-12-04
    • 2012-09-05
    相关资源
    最近更新 更多