Dynamically setting the image directory used by attachment_fu

It took me a while to figure this out and I don't see any wiki pages for attachment_fu so I figure I would just post this here.

I didn't like the way attachment_fu by default creates directories under a given directory for a specific class e.g.

item_image/1/img_1.jpg item_image/1/img_1_thumb.jpg item_image/2/img_2.jpg item_image/2/img_2_thumb.jpg item_image/3/img_3.jpg item_image/3/img_3_thumb.jpg

After a while you end up with ton of directories under the item_image directory. Instead I wanted the images to be grouped by the item object which has_many item_images. You can do that by adding the following two methods to the item_image object.

# Make sure the related item is associated to the thumbnail child before_thumbnail_saved do |record, thumbnail|     thumbnail.item = record.item end

def full_filename(thumbnail = nil)     # Just to be sure the ID gets set     raise "Missing Item ID" if item_id.nil?     file_system_path = (thumbnail ? thumbnail_class : self).attachment_options[:path_prefix].to_s     File.join(RAILS_ROOT, file_system_path, item_id.to_s, attachment_path_id, thumbnail_name_for(thumbnail)) end

and in your Item class you add a condition since it makes it easier to iterate over the images and for example call the image helpers

has_many :item_images,     :conditions => "parent_id is null"

Now all the directories will be grouped by the item_id.

Eric

Have you ever tried to have different path for thumbnails and originals? I have trouble with this because the thumbnail parameter is not set when the class calls full_filname internally.

Have you ever used the thumbnail_class attribute to move the thumbnails to a different model? I tried to do this, but with no luck.. I cannot find any docs on it either.

/MartOn

Yeah the documentation isn't so hot. Unfortuantely I haven't tried too change the thumbnail directory. Have you figured out how? As a quick hack you can probably manually set a variable on your custom image class. When the thumbnail is created the variable doesn't get copied and you might be able to use that to determine if it's the thumbnail or not.

I did a little write-up on how I'm using attachment_fu. I cover how to upload files without the subdirectories, and I also put up some code that I use with Capistrano. Maybe it'll help somebody else coming across this thread.

http://almosteffortless.com/2007/03/25/working-with-attachment_fu/