Rails: Redirect to page if condition

Kevin Brown picture Kevin Brown · Jul 1, 2011 · Viewed 9.7k times · Source

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.

Answer

Mohit Jain picture Mohit Jain · Jul 1, 2011

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