首页 > 解决方案 > 如何重定向到相同控制器动作的另一种格式?

问题描述

我有这个index方法在我的TasksController

def index
  @tasks = current_account.tasks
  @count = @tasks.length
  respond_to do |format|
    format.html do
      ...
    end
    format.zip do
      if @count > 100
        flash[:notice] = "Please reduce the number of tasks!"
        redirect_to :action => "index", :format => "html"
      else
        DownloadArchive.call(@tasks)
      end
    end
  end
end

html如果有超过 100 个任务,我如何呈现我的索引操作的版本?

我上面的代码不起作用。它不是重定向和显示闪存消息,而是下载html文件。我不明白为什么。如果可以,请你帮助我。

标签: ruby-on-railsrubyapplicationcontroller

解决方案


格式 zip 将下载一个文件,无论您在块中传递什么。如果您想确定 zip 文件是否甚至可以下载,您需要在处理格式zip请求之前执行此操作。您可能需要更改视图代码以不显示下载按钮或处理zip请求的任何内容。

def index
  @tasks = current_account.tasks
  @count = @tasks.length

  if @count > 100
    flash[:notice] = "Please reduce the number of tasks!"
    redirect_to :index and return
  end

  respond_to do |format|
    format.html do
      ...
    end
    format.zip do
        DownloadArchive.call(@tasks)
      end
    end
  end
end

推荐阅读