2011-05-12 181 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

相关问题