Topic: *Rails Beginner* Txt file upload to filesystem + DB
Hello all. I'm having some difficulty with the way that rails handles database writes vs. writes to hard drive. I can get my code to work to upload to the database, and to upload to the hard drive, but not both. I've tried replacing after_save :store_doc with just a direct call to the store_doc method, but that doesn't seem to work.
Can someone explain to me why this is? Without recommending a module to handle this, can someone guide me through writing a model that can accept a text upload, process the text into a DB and also write the file to a directory?
class Document < ActiveRecord::Base
attr_accessible :body, :extension, :filename, :upload
def upload=(incoming_file)
unless incoming_file.blank?
@incoming_file = incoming_file
self.filename = incoming_file.original_filename
self.extension = incoming_file.original_filename.split('.').last.downcase
if self.extension == 'txt'
self.body = incoming_file.read
else
self.body = 'wrong file type for direct uploading'
end
end
end
# def filename=(new_filename)
# write_attribute("filename", sanitize_filename(new_filename))
# end
# File.join is a cross-platform way of joining directories;
# we could have written "#{Rails.root}/public/doc_store"
DOC_STORE = File.join Rails.root, 'public', 'doc_store'
# where to write the first file to
def document_filename
File.join DOC_STORE, "#{id}.#{extension}"
end
# where to write the txt file to
def document_txtfilenamehas_document
File.join DOC_STORE, "#{id}.txt"
end
# return a path we can use in HTML for the docfile
def document_html_path
"/doc_store/#{id}.#{extension}"
end
# if a doc file exists, then we has a docfile
def has_document?
File.exists? document_filename
end
after_save :store_doc
private
def store_doc
logger.info "NOW inside store_doc"
if @incoming_file
#make the DOCSTORE dir if it doesn't already exist
FileUtils.mkdir_p DOC_STORE
#write out the data to the file
logger.info "write out the data to the file"
File.open(document_filename, 'wb') do |f|
f.write(@incoming_file.read)
end
# @incoming_file = nil
end
end
endLast edited by davidsmind (2013-02-07 06:10:45)