2013-10-15 46 views
1

我正在創建一個應用程序,允許用戶將數據存儲在其個人保管箱中的應用程序控制的受保護文件夾中。因此,每個用戶都需要在他們自己的個人保管箱帳戶中存儲和訪問文件。回形針 - 保管箱。我如何設置條件has_attached_file?

爲此,我想利用paperclip-dropbox gem進行存儲。它允許回形針直接上傳到保管箱:https://github.com/janko-m/paperclip-dropbox

以下是設置paperclip-dropbox gem的授權信息的代碼。 注意:此刻current_user不起作用。我只是在那裏概述當前設置的工作需要發生什麼。

Image.rb

has_attached_file :avatar, 
        :storage => :dropbox, 
        :dropbox_credentials => {app_key: DROPBOX_KEY, 
              app_secret: DROPBOX_SECRET, 
              access_token: current_user.token, 
              access_secret: current_user.secret, 
              user_id: current_user.uid, 
              access_type: "app_folder"} 

通知保管箱認證要求CURRENT_USER來獲取特定的憑據。

我知道current_user不應該從模型訪問,我想保持這種方式,所以任何人都可以幫助我弄清楚如何使用這個當前的設置來做到這一點?或者建議一個更好的選擇?

基本上,我需要根據每個用戶有條件地更改access_token,access_secret,& user_id。

謝謝!

回答

2

我打算回答我自己的問題,因爲其他答案太模糊不能接受 - 儘管他們走在正確的道路上。我認爲社區會選擇更多的代碼來支持它。

所以在這裏。要動態更改has_attached_file,您必須在附件模型中有一個user_id列,以便您不要調用current_user(如果沒有醜陋的黑客,這是不可能的)。然後您還需要一個belongs_to以完成用戶關聯。假設我將音頻文件附加到本示例的Song模型中。

獲取動態設置變量的關鍵是用after_initialize回調初始化附件。

Song.rb

belongs_to :user  
has_attached_file :audio 
after_initialize :init_attachment 

def init_attachment 
    self.class.has_attached_file :audio, 
    :storage => :dropbox, 
    :dropbox_credentials => {app_key: DROPBOX_KEY, 
          app_secret: DROPBOX_SECRET, 
          access_token: self.user.token, 
          access_token_secret: self.user.secret, 
          user_id: self.user.id 
          access_type: "app_folder"}, 
    :dropbox_options => {} 
end 

你,當然,自由設置你的協會不同,但是這是問題提出了工作代碼示例。

+0

我試圖達到同樣的目的,並想知道是否需要用戶從App Console請求API令牌密鑰和密鑰? – Seed

0

我認爲你應該做的第一件事就是設置關聯Image.belongs_to :user - 然後你可以簡單地使用user.token等等,而不是參考current_user

現在很難的部分。你不能簡單地鍵入:

access_token: user.token 

因爲selfImage類根本不給user方法(它的實例方法)進行響應。我的想法是修改這個gem,所以它可以接受lambdas作爲帶有附件實例的參數(例如)在調用時傳遞給lambda。問題是我不知道是否很難修改這個寶石。

+0

謝謝,我正在研究這個。 – Stone

0

剛剛發現這個資源,你可能獲得以下優勢:Ruby on Rails - Paperclip and dynamic parameters

更專門爲你,我想這可能提供一些線索到你在做什麼:

# AssetsController 
def create 
    @project = Project.find(params[:project_id]) 
    @asset = @project.assets.build(params[:asset]) 
    @asset.uploaded_by = current_user 

    respond_to do |format| 
    # all this is unrelated and can stay the same 
    end 
end 

的通知「@asset .uploaded_by「在控制器中設置?也許你可以將類似的變量傳遞給你的模型?我不知道具體如何做,但基本上可以在嘗試保存文件之前設置保存選項,讓您可以動態設置選項

+0

謝謝,我會看看。 – Stone