How do I stop controller execution after using redirect_to? (Using Rails)

前端 未结 5 738
日久生厌
日久生厌 2020-12-24 10:46

I have a controller with multiple actions that take :year and :month as attributes from the URL. I have made a private method check_date to check the date is valid and check

相关标签:
5条回答
  • 2020-12-24 11:28

    I think the OP is confused about the function of redirect_to.

    redirect_to will redirect at the end of the action. However, the rest of the controller function will execute as usual. All you have to do (as posted by other people) is to include a return, as you should any other function call.

    0 讨论(0)
  • 2020-12-24 11:29

    You can also do:

    return redirect_to :action => 'index'
    

    and

    return redirect_to :action => 'month_index', 
      :year => Date.today.year, 
      :month => Date.today.month,
      :type => params[:type]
    

    since it looks nicer than putting return on its own line (IMHO).

    0 讨论(0)
  • 2020-12-24 11:38

    You probably want to use filters.

    If you call your check_date as a before_filter in the controller, the fact that it rendered or redirected will prevent the controller from ever calling the action method. It ends there and then.

    0 讨论(0)
  • 2020-12-24 11:43

    You can throw in

    return false
    

    wherever you want the code execution in your action to stop

    0 讨论(0)
  • 2020-12-24 11:47

    redirect_to just tells rails what to render when it finishes. Rails will get confused if you add other render or redirect_to directives after the one you really want, so just return from the controller after the redirect_to - it's the 'normal' rails way to do things.

    0 讨论(0)
提交回复
热议问题