Rails: Saving the contents of a binary field to a file
-
06-09-2019 - |
Question
I have a model with a binary field that contains a file. I'd like to save this file to disk as part of a process I need to do. For some reason, I can't find anything on how to do this.
The model contains a filename field and a file_contents field. I'd like to do something like this:
model = SomeModel.find :first
model.file_contents.save_to_file(model.filename)
Any help would be appreciated!
Solution
I don't know why you'd want to call #save_to_file on the file contents instead of the model. Since you defined file_contents as an AR attribute I guess you want to save it to the DB and save it to disk. If that's the case you can simply add a method like this to your model:
class YourModel < ActiveRecord::Base
# ... your stuff ...
def save_to_file
File.open(filename, "w") do |f|
f.write(file_contents)
end
end
end
And then you'd simply do:
obj = YourModel.find(:first)
obj.save_to_file
OTHER TIPS
In ActiveRecord, the :binary
type that you use to define your column type in your migration is going to map to a blob
type in the database. So that wouldn't allow you to save to a file.
I think you would need to define a model class that is not a subclass of ActiveRecord::Base
and define a custom save_to_file
method for that class using the file i/o support in Ruby (the IO
class and its subclass, 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