問題描述
在保存到 Rails 模型之前打開臨時文件 (Open the temporary file before it is saved in Rails model)
Once you've uploaded a file, is it possible to open that file before the model is saved?
I'm using Paperclip to save files in the /public folder.
class Book < ActiveRecord::Base
before_save :open_it
has_attached_file :upload
def open_it
a_file = open(upload.url) # this doesn't work before save ?
# ...
end
end
參考解法
方法 1:
found it:
def model_method
f = open(self.upload.queued_for_write[:original].url)
end
Update:
Based on response from ecoologic, use .path
instead of .url
for more recent versions of the Paperclip gem
方法 2:
Close enough, but .url
didn't work for me, path
worked.
file = open(uploaded.queued_for_write[:original].path)
did the trick.
(by Clucking Turtle、Clucking Turtle、ecoologic)