Can I use redirect_to in a view in RoR?

后端 未结 5 1631
闹比i
闹比i 2021-01-04 00:28

In my app, I\'ve got a little box that appears on every page, checking on the status of requests made by the user. If a request is accepted at any time, then the user should

5条回答
  •  难免孤独
    2021-01-04 01:03

    The code in the view could be moved into the controller which would make redirect_to available.

    class ApplicationController < ActionController::Base
      before_action :check_for_accepted_offer
    
      def check_for_accepted_offer
        if Offer.any? { |o| o.accepted }
          redirect_to offer_path(:email => "email@gmail.com")
        end
      end
    end
    

    If the OP wanted to immediately change the URL when an offer is accepted then none of the Ruby code shown in the answers would help because it is only evaluated when the page is loaded. The OP would need to setup some kind of polling or push strategy to alert the browser when an offer has been accepted and then use the JavaScript redirect scheme posted in another answer:

    window.location.href="/logins/sign_up?email=<%= w.email %>"
    

    Although, this does not answer the question: "How can I use redirect_to in a view", I think this answer would ultimately have been more useful to the OP. I stumbled across someone using this answer to redirect to another page, when the redirect should have been performed in the controller.

提交回复
热议问题