I use this:
# schema for table ''images''
type TEXT -- for STI
original_filename TEXT
filename TEXT
content_type TEXT
# lib/file_record.rb
module FileRecord
def file=(file)
@temp_file = file
self.original_filename = file.original_filename.split(/\/|\\/).last
self.filename = "#{Time.now.to_f}-#{original_filename}"
self.content_type = file.content_type.rstrip # avoid trailing \r
end
def after_save
if @temp_file
if @temp_file.is_a?(StringIO)
@temp_file.rewind
File.open(path, "wb") { |f| f.write(@temp_file.read) }
else
FileUtils.copy @temp_file.local_path, path
end
FileUtils.chmod 0755, path
end
end
def uri
File.join("/", filename)
end
def path
File.join(File.expand_path(RAILS_ROOT), "public", uri)
end
end
# models/image.rb
class Image < ActiveRecord::Base
include FileRecord
def uri
File.join("/images", filename)
end
end
# models/article.rb
class Article < ActiveRecord::Base
has_many :images
# in your form: <%= file_field ''article'',
''image_file'' %>
def image_file=(file)
create_image(:file => file) unless file.size.zero?
end
end
This works so that if you put a file in your article_image_file field it
gets stuffed in /public/images, chmod''ed and the information about the
file on disk is stored in a table, works pretty well for me!
I''ve had some discussions on IRC about perhaps it''s time to
abstract
file storage so one doesn''t have to fiddle around with the File object
and discerning between StringIO and TempFile.
SIMEN BREKKEN / born to synthesize.
Mike Evans wrote:> I feel like this should be really easy but haven''t found the easy
> solution. What would be the most straightforward way of referencing
> the public/images directory from within a model (to facilitate image
> uploading)?
>
> Thanks,
> m