Back to Blog

Get in Touch

Custom Paths in attachment_fu

By Michael Bleigh September 5, 2007 in rails, attachment_fu, s3

Missing

If you've used attachment_fu (introduction here) in your Rails applications, you probably love its simple nature and its S3 integration. You may love less its very sparse documentation. When working on a project recently, I needed to save items to a path based on the owner of the attachment model, not the model itself.

The first attempt involved adding inline instance method calls to the :path_prefix option passed into has_attachment. This failed because has_attachment works on the class level, not the instance level.

After digging deeper, I found that the only thing one needs to do in order to change the path of a save in attachment_fu is to have a defined base_path method in your model. In the example of a user-based system with an avatar stored for each user, this might be a useful way to define your base_path:

class Avatar < ActiveRecord::Base
  belongs_to :user
  has_attachment :content_type => :image,
               :storage => :s3,
               :resize_to => '150x150'
				   	
  def after_save
    # Delete any existing avatars they have uploaded.
    Avatar.find(:all, :conditions => ["user_id = ?",self.user_id]).each do |ava|
      ava.destroy unless ava.id == self.id
    end
  end
    
  # Here we define base_path and therefore save to a custom location
  def base_path
    File.join("users", self.user.login, "avatar")
  end
	
  validates_as_attachment
end

This is a very simple example, but this provides a model of an avatar that will save to a folder under users/theusername with the filename the same as . For even further customization (including the filename), dig into the full_filename method in your storage solution of choice, and override in a similar fashion.

Just a quick Rails tip to help you along your attaching way.

Medium

Michael Bleigh

Michael has been with Intridea since 2007 and works to build Intridea's portfolio of products. With many years of experience working as both a designer and a developer, Michael specializes in helping to bridge the gap between the back-end development and the front-end design of a project. Michael is a prolific member of the Ruby on Rails community, having released popular open source libraries such as OmniAuth and spoken at conferences including RailsConf and RubyConf.

More posts by Michael Bleigh

Michael Bleigh

To the troubling idea isn't about what signal you're sending to your employee...

Michael Bleigh

Node.js has a pattern that I personally enjoy: if you require a directory, it...

Michael Bleigh

Last weekend I had the opportunity to speak at RubyConf 2012 about a topic th...