Skip to content

Instantly share code, notes, and snippets.

@ELLIOTTCABLE
Forked from augustl/application_helper.rb
Created October 29, 2008 15:52
Show Gist options
  • Save ELLIOTTCABLE/20725 to your computer and use it in GitHub Desktop.
Save ELLIOTTCABLE/20725 to your computer and use it in GitHub Desktop.
# The simplest thing that could possibly work. Will probably overwrite files if someone uploads
# a file that has the same file name as an already uploaded file. Requires the columns 'size' and
# 'content_type', see the 'store_file' method. You could obviously just remove those calls
# if you don't want to store the file size and the content type in the database.
class Attachment < ActiveRecord::Base
after_create :store_file
# Virtual attribute that stores the uploaded tempfile
attr_accessor :uploaded_file
private
def store_file
File.open(file_storage_location, "w") do |f|
f.write upload.read
end
self.size = uploaded_file.size
self.content_type = uploaded_file.content_type
end
def file_storage_location
File.join(Rails.root, 'public', 'attachments', uploaded_file.original_filename)
end
end
<% form_for @attachment, :multipart => true do |f| %>
<%= f.file_field :uploaded_file %>
<%= f.submit "Upload file" %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment