我几乎阅读了与Rails友好重定向相关的所有帖子,但在使用Devise进行身份验证后,我似乎无法弄清楚如何将用户重定向到之前的操作。
这就是我想做的事。
*请注意,我想重定向到之前的“操作”,而不仅仅是“页面”。换句话说,我希望在用户登录后已经执行了预期的操作。
这是我的代码。
class MissionsController < ApplicationController
before_filter :store_location
before_filter :authenticate_user!, :except => [:show, :index]
def vote_for_mission
@mission = Mission.find(params[:id])
if @mission.voted_by?(current_user)
redirect_to request.referer, alert: 'You already voted on this mission.'
else
@mission.increment!(:karma)
@mission.active = true
@mission.real_author.increment!(:userpoints) unless @mission.real_author.blank?
current_user.vote_for(@mission)
redirect_to request.referer, notice: 'Your vote was successfully recorded.'
end
end
end
在我的应用程序控制器中,
class ApplicationController < ActionController::Base
protect_from_forgery
def after_sign_in_path_for(resource)
sign_in_url = "http://localhost:3000/users/sign_in"
if (request.referer == sign_in_url)
session[:user_return_to] || env['omniauth.origin'] || request.env['omniauth.origin'] || stored_location_for(resource) || root_path
else
request.referer
end
end
private
def store_location
session[:user_return_to] = request.referer
end
我认为我的主要问题是,当用户需要登录时,vote_for_mission操作中的“request.referer”会无意中进入,因为前一页是登录页面。不知何故,我想将用户点击投票的页面保存为FOO - &gt;将投票操作保存为BAR - &gt;重定向到登录页面 - &gt;当用户登录时,重定向到BAR - &gt;执行BAR操作后,重定向到FOO。
提前感谢您的帮助!
答案 0 :(得分:4)
我通常做的是在ApplicationController中使用这样的方法:
def remember_location
session[:back_paths] ||= []
unless session[:back_paths].last == request.fullpath
session[:back_paths] << request.fullpath
end
# make sure that the array doesn't bloat too much
session[:back_paths] = session[:back_paths][-10..-1]
end
def back
session[:back_paths] ||= []
session[:back_paths].pop || :back
end
然后,在任何操作中(在您的情况下是登录处理程序),您只需
redirect_to back # notice, there is no symbol
并且在您希望能够跳回的每个操作中,只需致电
remember_location
我希望这会有所帮助。