1

I've got this index method in my 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

How can I render the html version of my index action if there are more than 100 tasks?

My code above doesn't work. Instead of redirecting and showing a flash message, it downloads the html file. I don't understand why. Please help me if you can.

Tintin81
  • 9,821
  • 20
  • 85
  • 178
  • 1
    The reason the html file is downloaded is that `format.zip` sets the [Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-tDisposition) header. So you override the header with `headers['Content-Disposition'] = "inline"`. But @lacostenycoder's answer is probally a better idea. – max Jan 19 '20 at 15:53

1 Answers1

6

Format zip will download a file, whatever you pass in the block. If you want to determine if the zip file should even be downloadable you'll need to do it before handling the format zip request. You will probably need to change your view code to not show the download button or whatever it is that's handling the zip request.

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
lacostenycoder
  • 10,623
  • 4
  • 31
  • 48