ruby:用户更新后错误运行操作

时间:2016-04-22 11:54:46

标签: ruby-on-rails ruby

我正在使用carrierwave上传保存在用户数据库中的文件。使用该文件更新后,我想调用将该文件复制到其他位置的操作。我的问题是,当我调用该操作时,它会给我这个错误(Errno::EISDIR - Is a directory @ rb_sysopen),因为它无法识别创建的文件,但是如果我刷新文件是在数据库中(如果我在其他位置调用copy_file操作)而不是在更新中它运行良好,但我想只在用户上传时复制文件。

这是我的两个操作,更新,并在运行更新后调用 copy_file

  def copy_file

    require "fileutils"
    my_dir = Dir['./public/'+current_user.personal_file_url.to_s]
    my_dir.each do |filename|
      # name = File.basename('data', '.xml')[0,4]
      dest_folder = "./public/files/"


      FileUtils.cp(filename, dest_folder + "data.xml")
     # File.rename(filename, dest_folder + "/" + "data" + File.extname(filename))


    end

    bat_file

    #redirect_to personal_performance_path

  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json


  def update  #upload personal file



    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to :back, notice: 'File was sucessfully uploaded!' }
        format.json { render :show, status: :ok, location: @user }

      #  copy_file  #make a copy of the uploaded file in public/files/data.xml for running in the bat file
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end

    end

 copy_file

  end

1 个答案:

答案 0 :(得分:0)

TempFile方法:

你可以通过几种方式做到这一点,我最好为它创建一个模块,你可以按照自己的意愿去做:

require 'tempfile'

module Temp

  def copy_file(file1, file2)
    file = TempFile.new(file1) #<= name your temp file
    # the easiest way to do this is just to open the files and append to them
    File.open(file2).each_line do |s|
      File.open(file) { |tmp| tmp.puts(s) }
      # you can choose to either truncate file2 or delete depending on what you need to do, you could also give it another argument in order to write to another file etc..
    end
   file.unlink #<= delete the tempfile
  end
end

Temp.copy_file('test', 'example.txt')

这是使用临时文件的基本理解

以下是复制模块的示例,您可以轻松地将临时文件集成到this