Kevin Brown
Kevin Brown

Reputation: 12650

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.

Upvotes: 3

Views: 10858

Answers (3)

Mohit Jain
Mohit Jain

Reputation: 43929

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

Upvotes: 5

diedthreetimes
diedthreetimes

Reputation: 4115

Redirect_to should be called from an action.

As an example,

class ApplicationController < ActionController::Base
  protect_from_forgery

  def index
    @offline = 'true'

    // Once you do the redirect make sure you return to avoid a double render error. 
    redirect_to :root && return if @offline == 'true' // Jed was right use a comparison 
  end
end

Take a look at the 'Redirect' docs

Upvotes: 1

glortho
glortho

Reputation: 13200

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

Upvotes: 0

Related Questions