在Rails中保存上传文件之前准备子目录?

时间:2015-11-26 15:30:28

标签: ruby-on-rails

这是我们在Rails 4.2中保存上传文件之前使用的方法:

   def prepare_subdir()     
       dir = Rails.root.join(@uploaded_file.storage_subdir).to_s
       FileUtils.mkdir_p(dir) unless File.directory?(dir)
   end

在调试中:

dir = "/upload/ext_construction_projectx_project/17"
@uploaded_file.storage_subdir = "/upload/ext_construction_projectx_project/17"
File.directory?(dir) returns true, even though only sub directory /upload/ exists on file system. No directory /ext_construction_projectx_project and 17 exist.

我们发现点击Save后没有保存任何文件。我们是否需要确保在调用save之前必须创建包括ext_construction_projectx_project17在内的所有子目录?

1 个答案:

答案 0 :(得分:1)

尝试没有前导斜杠,如下所示:

dir = "upload/ext_construction_projectx_project/17"

当然,除非你的上传目录实际上是root的子目录:

[1] pry(main)> dir = "/upload/ext_construction_projectx_project/17"
=> "/upload/ext_construction_projectx_project/17"
[2] pry(main)> Rails.root.join(dir)
=> #<Pathname:/upload/ext_construction_projectx_project/17>
[3] pry(main)> dir = "upload/ext_construction_projectx_project/17"
=> "upload/ext_construction_projectx_project/17"
[4] pry(main)> Rails.root.join(dir)
=> #<Pathname:/home/m/ruby/rails_app/upload/ext_construction_projectx_project/17>