我有一个包含文件的二进制字段的模型。我想这个文件保存到磁盘的过程中,我需要做的一部分。出于某种原因,我无法找到如何做这样的事情。

该模型包含一个文件名字段和file_contents字段。我想要做的是这样的:

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

任何帮助,将不胜感激!

有帮助吗?

解决方案

我不知道为什么你要叫#save_to_file上的文件内容而不是模型。既然你定义的 file_contents 的作为AR属性我想你想将它保存到数据库将其保存到磁盘。如果是这样的话,你可以像这样的方法简单地添加到您的模型:

 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

其他提示

在ActiveRecord的,你用你的迁移定义字段类型的:binary类型会映射到数据库中的一个blob类型。这样,才不会让您保存到一个文件。

我想你需要定义一个模型类,它是不是ActiveRecord::Base的子类,并使用该文件中定义为类的定制save_to_file方法I / O支持在Ruby中(该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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top