0

是否有一种简单的方法可以编写一个帮助方法来始终更新会话中先前访问的 url。我尝试了下面的方法,但保存的 url 始终是当前的。我希望能够在我的所有控制器中使用这个帮助器进行重定向。

#application_controller.rb
class ApplicationController < ActionController::Base
before_filter :my_previous_url

def my_previous_url
    session[:previous_url] = request.referrer
  end

helper_method :my_previous_url
end

我在用户控制器的更新方法中使用了它,如下所示,但它总是重定向到同一个打开的 url(有点像刷新被击中)。

def update
    if current_user.admin == true and @user.update(user_params)
      redirect_to my_previous_url, notice: "Password for User #{@user.username} has Successfully been Changed."
      return
    elsif current_user.admin == false and @user.update(user_params)
      session[:user_id] = nil
      redirect_to login_path, notice: "Password for User #{@user.username} has Successfully been Changed. Please Log-In Using the New Password."
      return
    end
    respond_to do |format|
      if @user.update(user_params)
    changed = true
        format.html { redirect_to logout_path }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end
4

1 回答 1

1

request.referer 不是您想要的,因为它将在页面重定向上设置,从而丢失您最初来自的页面。我认为您有一个隐含的要求,即它应该返回与当前不同的上次访问的 url ,是这样吗?另外,我认为您只想为 GET 请求设置它,否则您可能会将人们送回错误的 url,因为他们将被送回 GET 请求。我在这里假设这个 previous_url 的目的是给人们一个“返回”链接。

另外,不要将设置 previous_url 的方法与再次读取它的方法混为一谈。

我会这样做:

#application_controller.rb
class ApplicationController < ActionController::Base
  before_filter :set_previous_url
  helper_method :previous_url

  def set_previous_url
    if request.method == :get && session[:previous_url] != session[:current_url]
      session[:previous_url] == session[:current_url]
      session[:current_url] = request.url          
    end 
  end

  def previous_url
    session[:previous_url]
  end
end
于 2015-03-23T16:33:08.787 回答