September 6th, 2007
Custom Paths in attachment_fu
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.
Leave a Reply