logo

Tweaking Upload Location with Attachment_Fu

logo

So it seems like everyone’s agreeing that Attachment_Fu (tutorial here) is the Acts_As_Authenticated new model Liquid Metal Terminator version 2 replacement for handling file uploads. The only problem is that for an application I’m developing I need to specify a specific location for each upload based on a particular primary key id rather than just saving into a directory based on the file id.

So after gleaning from “almost effortless’” Working with attachment_fu article this is what I did:

[source:ruby]
class MyModel < ActiveRecord::Base
use_path = 'public/files/'

has_attachment :content_type => ‘application/pdf’,

:max_size => 2.megabytes,

:storage => :file_system,

:path_prefix => use_path

validates_as_attachment

validates_uniqueness_of :filename

before_create :change_filename

def change_filename

use_path = ‘public/files/’ + MyModel_id + “/”

self.location = use_path + filename

end

def full_filename

use_path = ‘public/files/’ + MyModel_id

File.join(RAILS_ROOT, use_path, filename)

end

end
[/source]
Yea, that’s it. For the “change_filename” method I set a default “use_path” variable because the model needed an initial value and wouldn’t process unless it was there. Then I overwrite the filename location in the database to the “use_path” value with the “MyModel_id” (this will be the folder) and the “filename” (value from the form) appended.

Finally, the “full_filename” method overwrites the value that the attachment_fu plugin uses for the default directory to the “use_path” directory I specified. And in true RubyOnRails form, all this functionality goes in the Model and not in the controller.

Hope this helps someone in the great “out there”.

(DISCLAIMER: Yea, there may be a better way of doing this, in fact I know I can re-factor the use_path for both functions … and I admit I’m no expert, so feel free to let me know. Just, please be kind to the Rich-man.)

Technorati Tags:

blog comments powered by Disqus
logo
logo
Powered by Wordpress