Rails重定向到登录前想要查看的页面用户
我正在尝试将用户重定向回他们在登录之前尝试访问的页面(该页面仅供用户查看)。
我将从一个针对我的旅行新动作的前filter开始:
before_filter :authenticate, :only => [:new, :create, :edit, :update, :destroy]
def authenticate deny_access unless signed_in? end def deny_access store_location redirect_to login_path, :notice => "Please log in to access this page." end def store_location session[:return_to] = request.fullpath end
这是我的sessions_controller.rb中的new和create操作
def new @title = "Log in" end def create user = User.authenticate(params[:session][:email].downcase, params[:session][:password]) if user.nil? flash.now[:error] = "Invalid email/password combination." @title = "Log in" render 'new' else sign_in user redirect_back_or(root_path) end end def redirect_back_or(default) redirect_to(session[:return_to] || default) clear_return_to end
谢谢!
编辑:删除了MaddHacker的代码版本,因为这不是我想要的。
我通常使用before_filter之类的
def login_required session[:return_to] = request.fullpath redirect_to(login_page_url) end
然后当我的登录完成时,我会在会话中查找return_to:
def login # user validation of login here url = session[:return_to] || root_path session[:return_to] = nil url = root_path if url.eql?('/logout') logger.debug "URL to redirect to: #{url}" redirect_to(url) end
好吧,首先,您需要在从未授权页面重定向到登录页面之前调用store_return_to方法。 然后我认为您需要将方法描述更改为def redirect_back_or_default(default = root_path)
以便参数变为可选。
顺便说一句,我不能理解为什么你需要将参数传递给该方法,如果它只是一个默认值,你可以在方法本身硬编码。
- 在Ruby on Rails 4(欧盟立法)中强制禁用cookie,直到用户(重新)接受ToS
- REXML :: Document.new我们可以在这行上给出编码参数吗?
- 在rails应用程序的前端获取实时日志
- Project的未定义方法`model_name’:Class
- CanCan ::能在哪里定义current_user方法?
- 获取资产管道路径中的Gem供应商文件
- 在生成mass_assignment错误之前,使用Hash#exclude排除控制器操作中的嵌套表单字段?
- rails多态关联(遗留数据库)
- 连接失败:localhost(Errno :: ECONNREFUSED:连接被拒绝 – 连接(2))