开发者

Rails: Redirect to page if condition

开发者 https://www.devze.com 2023-03-16 16:06 出处:网络
I want to redirect a user if a condition is true: class ApplicationController < ActionController::Base

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.


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消