2016-09-15 27 views
0

在一個應用程序中,我想將公共文件URL發送到after_create回調中的服務。所以,代碼(簡化)看上去像這樣:Carrierwave在回調中返回tmp文件的路徑而不是實際的

class UserProfile < ApplicationRecord 
    mount_uploader :video, VideoUploader 
    after_create :send_url_to_service 

    private 

    # Just logs the URL 
    def send_url_to_service 
    Rails.logger.info video.url 
    end 
end 

令我沮喪,上傳之後,send_url_to_service回調始終記錄緩存的文件路徑 - 像'uploads/tmp/1473900000-123-0001-0123/file.mp4'而不是'uploads/user_profiles/video/1/file.mp4'。我試圖編寫一個方法來從實際的文件路徑中構建URL,但它不起作用,因爲該文件還沒有。

所以,問題是,你如何在這樣的情況下獲得最終文件的URL?

P. S.請注意,這是一個自我回答的問題,我只是想分享我的經驗。

回答

2

對我來說,解決辦法是使用after_commit ..., on: :create回調,而不是after_create

class UserProfile < ApplicationRecord 
    mount_uploader :video, VideoUploader 
    after_commit :send_url_to_service, on: :create 

    private 

    # Just logs the URL 
    def send_url_to_service 
    Rails.logger.info video.url 
    end 
end 

答案是很明顯的,雖然我浪費了很長一段時間它周圍徘徊。解釋很簡單:after_commit只有在所有信息成功保留後,回調纔會觸發。在我的情況下,該文件還沒有保存到存儲目錄(在after_create階段) - 這就是爲什麼我得到臨時文件的URL而不是實際的。希望這有助於節省時間。

相關問題