【问题标题】:How to redirect to another format of the same controller action?如何重定向到相同控制器动作的另一种格式?
【发布时间】:2020-01-19 15:22:27
【问题描述】:

我的TasksController 中有这个index 方法:

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

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

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

【问题讨论】:

  • 下载html文件的原因是format.zip设置了Content-Disposition标头。所以你用headers['Content-Disposition'] = "inline" 覆盖标题。但@lacostenycoder 的回答可能是一个更好的主意。

标签: ruby-on-rails ruby applicationcontroller


【解决方案1】:

格式 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 2015-05-18
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多