Search code examples
ruby-on-railsconditional-statementsreroute

Rails: Redirect to page if condition


I want to redirect a user if a condition is true:

class ApplicationController < ActionController::Base
  @offline = 'true'
  redirect_to :root if @offline = 'true'
  protect_from_forgery
end

Edit This is what I'm trying now with no success. The default controller is not the Application Controller.

class ApplicationController < ActionController::Base
    before_filter :require_online 

    def countdown

    end

private
  def require_online
    redirect_to :countdown
  end

end

This gives a browser error Too many redirects occurred trying to open “http://localhost:3000/countdown”. This might occur if you open a page that is redirected to open another page which then is redirected to open the original page.

If I add && return, the action never gets called.


Solution

  • In addition to Jed's answer

    Need the comparison operator, not the assignment operator:

     redirect_to :root if @offline == 'true'
    

    If you're having further difficulties, simplify tests with:

     redirect_to(:root) if @offline == 'true'
    

    Or maybe it should be a true boolean and not a string?

     redirect_to :root if @offline
    

    class ApplicationController < ActionController::Base
       before_filter :require_online 
    
     private
        def require_online
           redirect_to(:root) && return if @offline == 'true'
        end
     end