如何将文件存储在carrierwave的公共文件夹旁边?

Carrierwave默认接受上传者中store_dir生成的url,并store_dir指定rails应用程序的公共文件夹的路径并存储文件。

例如,如果

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

然后该文件存储在public/uploads/:attachment_id

如果尝试将存储的文件移出公用文件夹,它仍然保存在公用文件夹中。 有没有人知道如何将文件存储在公共文件夹之外?

最简洁的方法是设置CarrierWave根选项

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

然后store_dir将在此根目录中使用。

我意识到这不是一个当前的问题,但我偶然发现它寻找其他东西。 答案就是使用Rails.root,例如:

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

一个更清洁的解决方案是定义:

 def store_dir nil end 

查看文档

在商店里面,你也可以这样做:

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

更改config_root的解决方案对我不起作用。

如果有人只需要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