Generating a unique file path with Polymorphic Paperclip
paperclip, polymorphism, ruby-on-rails
Solution
Use Paperclip interpolations:
file config/initializers/paperclip.rb:
module Paperclip
module Interpolations
def user_id(attachment, style)
current_user.id
end
end
end
has_ attached_file option:
:url => "/assets/:user_id/:id/:style/:filename"
(The syntax changed from Paperclip 2.x to 2.3; :path is not necessary; Use the latest version and have a look at the source, it's quite well documented.)
Problem
I'm running into an issue with different users uploading files with the same name being overwritten with the Polymorphic Paperclip plugin. What I'd like to do is inject the current user's ID into the URL/path. Is this possible? Would I be better off generating a random name? Here are my current :url and :path parameter values in asset.rb: ``` :url => "/assets/:id/:style/:basename.:extension", :path => ":rails_root/public/assets/:id/:style/:basename.:extension" ``` What I'd like to be able to do is this: ``` :url => "/assets/#{current_users_id}/:id/:style/:basename.:extension", :path => ":rails_root/public/assets/#{current_users_id}/:id/:style/:basename.:extension" ```