将数据发布到另一个控制器的操作的正确方法是什么?

时间:2017-05-09 12:34:36

标签: ruby-on-rails parameters controller

我有一个自定义Rails表单,如下所示:

<form action="/download/zip" id="multifile" method=POST>
  <!-- Here is a react component that makes a loop of every record I have of uploaded files, with a checkbox before each of them, that would look like the following -->

    <label><input type="checkbox" value={ this.props.file.path } /> { this.props.file.filename } </label>
    <input type="submit" value="Download" />
</form>

我选择不使用form_for,因为我想提交的值没有链接到模型(但如果需要,我可以使用它)。

外部控制器用于创建所选文件的zip。如果我将方法修改为'get'并且我要求下载所有内容,它就可以工作。

到目前为止,它的外观如下:

class DownloadController < ApplicationController
  require 'zip'

  def zip

    abort @params.inspect # returns 'nil'

    zip_tmp = File.new("#{Rails.root}/public/zip-#{Time.now.strftime('%d%m%Y')}.zip", 'w+')

    Zip::File.open(zip_tmp.path, Zip::File::CREATE) do |zipfile|
      FileDetail.all.each do |file| # This works with route set to get
        zipfile.add(file.path.split('/')[-1], '/home/username/DEV/rails-react-project/public' + file.path)
      end
    end

    send_file "#{Rails.root}/public/zip-#{Time.now.strftime('%d%m%Y')}.zip"
  end

  private

  def params
    @params
  end
end

我正确地被重定向到控制器,但是当我检查是否有一些工作数据时,我没有回来。

这样做的“正确”方法是什么?

提前谢谢

(P.S。我知道如果它有效,我会对这个实际代码有一些问题,但是通过参数获取数据会很好开始)

1 个答案:

答案 0 :(得分:1)

我看到它已经评论了错误,但我想编辑你的代码并发布答案,因为它会对其他人有所帮助。

表格:

<form action="/download/zip" id="multifile" method=POST>
  <!-- Here is a react component that makes a loop of every record I have of uploaded files, with a checkbox before each of them, that would look like the following -->

    <label>
      <input type="checkbox" name="my_param_name[]" value={ this.props.file.path } /> { this.props.file.filename } 
    </label>
    <input type="submit" value="Download" />
</form>

控制器:

class DownloadController < ApplicationController
  require 'zip'

  def zip

    # This will return array of files user has selected in form
    # You can use this to process further to generate zip
    files_list = params[:my_param_name] 

    suffix = Time.now.strftime('%d%m%Y')
    zip_file_name = "#{Rails.root}/public/zip-#{suffix}.zip"
    zip_tmp = File.new(zip_file_name, 'w+')

    Zip::File.open(zip_tmp.path, Zip::File::CREATE) do |zipfile|
      FileDetail.all.each do |file| # This works with route set to get
        zipfile.add(file.path.split('/')[-1], '/home/username/DEV/rails-react-project/public' + file.path)
      end
    end

    send_file zip_file_name
  end

end

注意:我没有在本地测试代码,因此可能会出错。如果您遇到错误,请回答答案

希望这有帮助!