如何将文件存储在 carrierwave 中的公用文件夹之外



默认情况下,Carrierwave在上传器中接收store_dir生成的URL,并在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

最新更新