views:

600

answers:

1

By default Attachment Fu stores uploaded files in "public/#{table_name}". I want to modify this to be something like "public/#{table_name}/#{site_id}", where site_id is a property of the model. Note that I've tried using self.site_id and both fail.

has_attachment :storage => :file_system, 
               :max_size => 25.megabytes,
               :path_prefix => "public/#{table_name}/#{site_id}",
               :thumbnails => { 
                 :large => '256x256>', 
                 :medium => '128x128>', 
                 :small => '64x64>' 
               }

I receive "undefined local variable or method site_id" error messages. Removing the #{site_id} component from the :path_prefix works fine and the initialize method is run. I can access the site_id as expected.

I have an initialize method which looks like this:

def initialize(site_id = nil)
  super(nil)
  self.site_id ||= site_id
end

I instanciate the object via the Rails console like this:

r = Resource.new(100)

Is the has_attachment method running before my initialize method? How can I pass a parameter into the :path_prefix dynamically when the model is instantiated?

+2  A: 

site_id is a dynamic value, so you can't set this in the class. You'll want to redefine #full_filename in your model. The current definition looks like:

def full_filename(thumbnail = nil)
  file_system_path = (thumbnail ? thumbnail_class : self).attachment_options[:path_prefix].to_s
  File.join(RAILS_ROOT, file_system_path, *partitioned_path(thumbnail_name_for(thumbnail)))
end

Change the final line to something like:

File.join(RAILS_ROOT, file_system_path, site_id.to_s, *partitioned_path(thumbnail_name_for(thumbnail)))
technoweenie