代码之家  ›  专栏  ›  技术社区  ›  Tim Sullivan

Rails:将二进制字段的内容保存到文件中

  •  2
  • Tim Sullivan  · 技术社区  · 16 年前

    model = SomeModel.find :first
    model.file_contents.save_to_file(model.filename)
    

    任何帮助都将不胜感激!

    2 回复  |  直到 16 年前
        1
  •  2
  •   eggdrop    16 年前

    :binary 用于在迁移中定义列类型的类型将映射到 blob 在数据库中键入。这样就不允许保存到文件中。

    我认为您需要定义一个不是 ActiveRecord::Base save_to_file 方法使用Ruby中的文件i/o支持( IO 类及其子类, File ).

    class SomeModel
     attr_accessor :file
     attr_accessor :contents
    
     def initialize
      @file = File.new("file.xyz", "w")
     end
    
     def save_and_close
      @file << contents
      @file.close
     end
    end
    
        2
  •  2
  •   Federico Builes    16 年前

    文件内容 作为AR属性,我猜您希望将其保存到DB中 将其保存到磁盘。如果是这种情况,您可以简单地向模型中添加如下方法:

     class YourModel < ActiveRecord::Base
       # ... your stuff ...
       def save_to_file
         File.open(filename, "w") do |f|
           f.write(file_contents)
         end
       end
     end
    

    obj = YourModel.find(:first)
    obj.save_to_file