Carrierwave + Rails 5:读取目录与存储目录

时间:2017-05-11 22:40:17

标签: ruby-on-rails carrierwave

Carrierwave的enter link description here提供了Carrierwave上传文件的目录和Carrierwave查找文件的目录。但是,我想知道是否有定义类似read_dir的方法,这将是Carrierwave查找文件的路径,并保留store_dir仅用于存储文件。

我知道这可能没有多大实际意义,但我只是想知道。

1 个答案:

答案 0 :(得分:3)

您可以根据对象的某些条件计算store_dir。您还可以在需要其他目录时设置此条件。例如:

class MyModel < ActiveRecord::Base
  attr_accessible :use_directory_for_storing

  mount_uploader :file, MyFileUploader
end

class MyFileUploader < CarrierWave::Uploader::Base
  # ...
  def store_dir
    if model.use_directory_for_storing
      "some/directory/for/storing"
    else
      "some/directory/for/reading"
    end
  end
end

# Usage

object = MyModel.new(params)
object.use_directory_for_storing = true

object.save # the file will be stored in ".../some/directory/for/storing/" directory

object = MyModel.last
# will look for the file in the ".../some/directory/for/reading/" directory
object.file.path # => ".../some/directory/for/reading/..."