I'm implementing a file upload form. It work but its a little bit
glitchy. For example, when the file upload it writes the the database
twice. The second time it writes its a null record. I can see why
but I'm not exactly sure how to work around this. Any suggestions?
#new.html.haml
= error_messages_for @attachment
= form_for(:attachment, :action=>'create') do #...@attachment, :action =>
url(:attachment, :create)) do
%p
= file_field :attachment, :label => "File"
= submit "Create"
#models/attachment.rb
require 'uploads_helper'
class Attachment
include DataMapper::Resource
include Attachable
property :id, Serial
property :filename, String
property :content_type, String
property :size, Integer
property :attachable_id, Integer
property :attachable_type, String
property :description, Text
property :location, String
has n, :attachment_tags
has n, :tags, :through => :attachment_tags
def url
"/uploads/#{self.id}/#{self.filename}"
end
end
#helper/uploads_helper.rb
require 'ftools'
module Attachable
include FileUtils
def attachments
@attachments = Attachment.all(:attachable_type =>
self.class, :attachable_id => self.id)
end
def attachment
@attachment
end
def attachment=(value)
@attachment = value
unless value.empty?
puts "creating file"
attachment = Attachment.create( :attachable_type => self.class,
:attachable_id => self.id,
:filename =>
@attachment[:filename],
:content_type =>
@attachment[:content_type],
:size => @attachment[:size]
)
begin
File.makedirs("public/uploads/#{attachment.id}")
mv(@attachment[:tempfile].path, "public/uploads/
#{attachment.id}/#{attachment.filename}")
rescue
#rescue stuff
end
end
debugger
@attachment
end
protected
# Partition the path according to the ida
def partitioned_path(id)
# *("%06d" % id).scan(/.../)
end
end
#controllers/attachment.rb
.
.
.
def create(attachment)
@attachment = Attachment.new(attachment) #enters module - saves
file and writes to db
if @attachment.save # writes empty record to db
redirect resource(@attachment), :message => {:notice =>
"Attachment was successfully created"}
else
message[:error] = "Attachment failed to be created"
render :new
end
end
.
.
.
--
You received this message because you are subscribed to the Google Groups
"merb" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to [email protected].
For more options, visit this group at http://groups.google.com/group/merb?hl=en.