I’m trying to create a document upload system, where most of the code is
the super class Document and just the path to file on the system is
controlled by the sub classes. When I attempt to use my code, I get the
following when I try to save the document.
can’t dump anonymous class Class
Any ideas?
** Migration **
class CreateDocuments < ActiveRecord::Migration
def self.up
create_table :documents do |t|
t.column :type, :string
t.column :name, :string
t.column :file_path, :string
t.column :content_type, :string
t.column :created_on, :timestamp
# attributes for type=“AssociationDocument”
t.column :association_id, :integer
# attributes for type=“LocationDocument”
t.column :location_id, :integer
end
end
def self.down
drop_table :documents
end
end
** Models **
class Document < ActiveRecord::Base
attr_accessor :uploaded_file
def after_create
if !File.exists?(File.dirname(self.file_path))
Dir.mkdir(File.dirname(self.file_path))
end
if @uploaded_file.instance_of?(Tempfile)
FileUtils.copy(@uploaded_file.local_path, self.file_path)
else
File.open(self.file_path, "wb") { |f| f.write(@uploaded_file.read)
}
end
end
def after_destroy
if File.exists?(self.file_path)
File.delete(self.file_path)
end
end
def file=(uploaded_file)
@uploaded_file = uploaded_file
self.file_path = sanitize_filename(@uploaded_file.original_filename)
self.content_type = @uploaded_file.content_type
end
private
def new_filename(file_name)
idx = file_name.rindex “.”
self.name.gsub(/[^\w._]/, ‘_’) + file_name[idx, file_name.length -
idx]
end
def sanitize_filename(file_name)
File.expand_path("#{RAILS_ROOT}/public/documents/#{new_filename(file_name)}")
end
end
class GlobalDocument < Document
validates_uniqueness_of :name, :scope => :type
private
def sanitize_filename(file_name)
File.expand_path("#{RAILS_ROOT}/public/documents/global/#{new_filename(file_name)}")
end
end
** Controller **
def documents
@associations = Association.find(:all, :order => [ “name” ])
@association_documents = AssociationDocument.find(:all, :include =>
[ “association” ])
@global_documents = GlobalDocument.find_all()
@new_document = GlobalDocument.new
end
def save_global_document
doc = GlobalDocument.new(params[:new_document])
if doc.save
flash[:notice] = “#{doc.name} was saved”
else
flash[:error] = doc.errors.full_messages.join("
")
end
redirect_to :action => :documents
end
** View **
documents.rhtml
<%= form_tag({ :action => :save_global_document }, { :multipart =>
true }) %>
| Name: | <%= text_field :new_document, :name, :class => “fixed” %> |
| File: | <%= file_field :new_document, :file, :class => “fixed” %> |
| <%= submit_tag “Upload file” %> |
<%= end_form_tag %>