Question

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"
Was it helpful?

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.)

OTHER TIPS

Every time I see the word random and it relates to strings, I think GUID. Perhaps they could work for you.

for me it didnt work bypaperclip.rb but it works like this:

In the model class:

class Micropost < ApplicationRecord
  Paperclip.interpolates :user_id do |attachment, style|
    attachment.instance.user_id
  end

 has_attached_file  :pic1, 
    :url => "/Microposts/:user_id/:style/:basename.:extension"

In case if you want to do it by Paperclip interpolations you should find a path like this: first find gem file path. type this in your terminal:

$ gem env

Then, it will show you a path in "- GEM PATHS:" in my case this was the path :

:/usr/local/lib/ruby/gems/2.4.0/gems/paperclip-5.0.0/lib/paperclip

In this direction you can find "paperclip.rb" .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top