Skip to content

Instantly share code, notes, and snippets.

@vangberg
Forked from augustl/application_helper.rb
Created November 3, 2008 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vangberg/21994 to your computer and use it in GitHub Desktop.
Save vangberg/21994 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.
#
# If you need a fancy name (in the spirit of 'paperclip' and 'attachment_fu'), you can call this code
# 'fucking_simple_fu' so that you can refer to this code and look like a cool kid on teh block.
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 uploaded_file.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