在没有使用Devise的已经signed_in用户的rails中重定向root_path [英] Redirect root_path in rails for already signed_in user without using Devise

查看:477
本文介绍了在没有使用Devise的已经signed_in用户的rails中重定向root_path的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有 root_path root'home#mainPage',虽然用户已登录,但他可以访问 http:// localhost:3000 / 我不想要。所以我正在关注 http://stackoverflow.com/a/8739874/3786657 回答添加此功能,我得到未定义的方法user_signed_in?用于AuthenticatedUser:Class 。我使用的是Rails 4.2.0

In my application i have root_path root 'home#mainPage' and though a user is signed in , he can accesss http://localhost:3000/ which i dont want. So i am following http://stackoverflow.com/a/8739874/3786657 answer to add this feature and i am getting undefined method user_signed_in? for AuthenticatedUser:Class. I am using Rails 4.2.0

我的路线:

  constraints(AuthenticatedUser) do 
    root :to => "users#show", as: :authenticated
  end

  root 'home#mainPage'

Lib / authenticated_user.rb:

class AuthenticatedUser
  def self.matches?(request)
    user_signed_in?
  end
end

application_helper.rb / p>

application_helper.rb

module ApplicationHelper
    def user_signed_in?
        !!session[:user_id]
    end
    def current_user
        User.find(session[:user_id])
    end
end

配置/ application.rb

config.autoload_paths << Rails.root.join('lib')


推荐答案

user_signed_in? ApplicationHelper 中定义的方法不可用于 AuthenticatedUser 。因为你可以从请求中获取会话,我只需直接在 AuthenticatedUser 中查看:

The user_signed_in? method defined in ApplicationHelper is not available to AuthenticatedUser. Since you can get the session from the request I would just check it directly in AuthenticatedUser:

class AuthenticatedUser
  def self.matches?(request)
    !!request.session[:user_id]
  end
end

这篇关于在没有使用Devise的已经signed_in用户的rails中重定向root_path的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆