2011-05-12 186 views
18

默認情況下,Carrierwave接收上傳器中由store_dir生成的url,並在rails應用程序的公用文件夾的前面加上並保存文件。如何將文件保存在carrierwave的公用文件夾中?

例如,如果

def store_dir 
    "uploads/#{model.id}" 
end 

然後將文件存儲在public/uploads/:attachment_id

如果一個人試圖保存的文件移出公用文件夾的還是它保存在公用文件夾。有沒有人有關於如何將文件存儲在公用文件夾外的想法?

回答

34

這樣做最徹底的方法,是通過設置CarrierWave根選項

CarrierWave.configure do |config| 
    config.root = Rails.root 
end 

然後store_dir將這個根內使用。

12

我意識到這不是一個真正的當前問題,但我偶然發現它尋找別的東西。答案很簡單,使用Rails.root,如:

def store_dir 
    "#{Rails.root}/private/files/#{model.id}" 
    end 
+0

要小心,因爲很可能會遇到「Sprockets :: FileOutsidePaths」錯誤。 – Tommyixi 2016-05-04 01:04:04

0

在店內DIR你也可以做這樣的事情:

def store_dir 
    "#{Rails.root.join('public', 'system', 'uploads')}/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" 
end 

改變config_root我沒有工作的解決方案。

0

如果有人需要,只是對RSpec的,然後就去做

describe SomeClass do 
    before do 
    CarrierWave.stub(:root). 
     and_return(Pathname.new "#{Rails.root}/tmp/fake_public") 
    end 

    it { ... } 
end 

,如果你想,對於所有的測試

# spec/spec_helper.rb 
RSpec.configure do |config| 
    # ... 
    config.before :each do 
    # ... 
    CarrierWave.stub(:root).and_return(Pathname.new "#{Rails.root}/tmp/public") 
    end 
end 
5

一個更清潔的解決方案是定義:

def store_dir 
    nil 
end 

請參閱the docs

+0

plus1這是「官方」的方式 – 2015-09-10 18:07:59

相關問題