2009-07-18 92 views
3

我遇到了一個問題,不同用戶上傳的文件被同名回形針回形針插件覆蓋。我想要做的是將當前用戶的ID注入到URL /路徑中。這可能嗎?我會更好地生成一個隨機名稱嗎?使用Polymorphic回形針生成一個唯一的文件路徑

這裏是我當前的:url和:在asset.rb程參數值:

:url => "/assets/:id/:style/:basename.:extension", 
:path => ":rails_root/public/assets/:id/:style/:basename.:extension" 

我想怎麼能夠做到的是:

:url => "/assets/#{current_users_id}/:id/:style/:basename.:extension", 
:path => ":rails_root/public/assets/#{current_users_id}/:id/:style/:basename.:extension" 

回答

6

使用回形針插值:

文件配置/初始化/ paperclip.rb:

module Paperclip 
    module Interpolations 
    def user_id(attachment, style) 
     current_user.id 
    end 
    end 
end 

Has_或許有幫助attached_file選項:

:url => "/assets/:user_id/:id/:style/:filename" 

(語法從回形針2.X改爲2.3 ;:路徑不是必需的;使用最新版本並查看源代碼,這是非常有據可查的。)

+1

如果您使用的是設計,您不能使用current_user,而是如果您在模型中引用了用戶表(例如user_id),則可以這樣做:attachment.instance.user_id – 2012-11-05 10:26:55

0

每次我看到這個詞隨機,它涉及到字符串,我覺得GUID。也許他們可以爲你工作。

0

對我來說,沒有工作bypaperclip.rb但它的工作原理是這樣的:

在模型類:

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" 

在情況下,如果你想通過回形針插值做到這一點,你應該找到像這樣的路徑: 先找到gem文件路徑。在終端輸入:

$ gem env 

然後,它會告訴你在路徑「 - 創業板的路徑:」在我的案件 這是路徑:

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

在這個方向上,你可以找到「paperclip.rb」。