redirect_to != return

后端 未结 6 1404
陌清茗
陌清茗 2020-12-07 22:13

I\'m looking for some clarification regarding the behaviour of redirect_to.

I have this code:

if some_condition
   redirect_to(path_one)         


        
相关标签:
6条回答
  • 2020-12-07 22:29

    Yes, you need to return from method when doing redirect. It actually only adds appropriate headers for the response object.

    You can write more rubyish way:

    if some_condition
        return redirect_to(path_one)
    end
    
    redirect_to(path_two)
    

    or other way:

    return redirect_to(some_condition ? path_one : path_two)
    

    or another way:

    redirect_path = path_one
    
    if some_condition
        redirect_path = path_two
    end
    
    redirect_to redirect_path
    
    0 讨论(0)
  • 2020-12-07 22:35

    From http://api.rubyonrails.org/classes/ActionController/Base.html:

    If you need to redirect on the condition of something, then be sure to add “and return” to halt execution.

    def do_something
      redirect_to(:action => "elsewhere") and return if monkeys.nil?
      render :action => "overthere" # won't be called if monkeys is nil
    end
    
    0 讨论(0)
  • 2020-12-07 22:36

    To consolidate the "rubyish way" example in Eimantas' answer to two lines of code:

    return redirect_to(path_one) if some_condition
    
    redirect_to(path_two)
    
    0 讨论(0)
  • 2020-12-07 22:41

    If you'd like to define the redirect within a method or helper function and early return in your controller:

    ActionController::Metal#performed? - Tests if render or redirect has already happened:

    def some_condition_checker
      redirect_to(path_one) if some_condition
    end
    

    Call it like this:

    some_condition_checker; return if performed?
    
    redirect_to(path_two)
    
    0 讨论(0)
  • 2020-12-07 22:45

    You can also do

    redirect_to path_one and return
    

    which reads nice.

    0 讨论(0)
  • 2020-12-07 22:52

    It's worth noting there is no need to return unless you have any code after redirect_to, as in this example:

    def show
      if can?(:show, :poll)
        redirect_to registrar_poll_url and return
      elsif can?(:show, Invoice)
        redirect_to registrar_invoices_url and return
      end
    end
    
    0 讨论(0)
提交回复
热议问题