Collecting all attachments using Paperclip
Paperclip is a great way to allow file uploads in your Rails application. However, it doesn’t give you much in the way of tools to move those files around once they’re on the server, so I concocted a little strategy for doing so.
I tried to get this into Paperclip itself, but it looks like I’m the only person who actually needed it, but I’m hoping this blog post will come in handy for someone eventually.
If you have a User model with an avatar attachment, you’d need the following:
class User < ActiveRecord::Base
has_attached_file :avatar # etc...
def avatars
versions = self.avatar.styles.keys << :original
versions.map do |version|
{:path => self.avatar.path(version), :url => self.avatar.url(version)}
end
end
end
This would give you an array to access the path and url for each avatar like so:
User.last.avatars.each do |avatar|
puts avatar[:path]
end