Search code examples
ruby-on-railsrubyapplicationcontroller

How to redirect to another format of the same controller action?


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.


Solution

  • 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