How to store files out side the public folder in c

2019-03-14 16:40发布

Carrierwave by default takes in the url generated by store_dir in the uploader and prepends the path to the public folder of the rails application and stores the files.

For example if

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

then the file is stored at public/uploads/:attachment_id

If one tries to move the stored files out of the public folder still it saves in the public folder. Does anyone have an idea of how to store the files outside the public folder??

5条回答
看我几分像从前
2楼-- · 2019-03-14 17:01

I realize this isn't really a current question, but I stumbled on it looking for something else. The answer is simply to use Rails.root, eg:

  def store_dir
    "#{Rails.root}/private/files/#{model.id}"
  end
查看更多
干净又极端
3楼-- · 2019-03-14 17:01

A much more cleaner solution would be to define:

def store_dir
  nil
end

See the docs

查看更多
乱世女痞
4楼-- · 2019-03-14 17:07

the cleanest way to do this, is by setting the CarrierWave root option

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

then store_dir will be used inside this root.

查看更多
放我归山
5楼-- · 2019-03-14 17:11

If someone need that just for RSpec then just do

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

  it { ... }
end

if you want that for all your tests

# 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
查看更多
Summer. ? 凉城
6楼-- · 2019-03-14 17:13

Inside the store dir you can also do something like this:

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

the solution of changing the config_root didn't work for me.

查看更多
登录 后发表回答