简体   繁体   English

尝试重定向用户(如果他们已登录)时遇到问题

[英]Having problems trying to redirect user if they are logged in

I'm using Rails 4.2.5. 我正在使用Rails 4.2.5。 If a user is logged in, I want to redirect them if they visit http://localhost:3000/ to http://localhost:3000/user_objects . 如果用户已登录,则如果他们访问http:// localhost:3000 /http:// localhost:3000 / user_objects ,我想将他们重定向。 So I have added this to my config/routes.rb file 所以我已经将此添加到我的config / routes.rb文件中

  constraints(AuthenticatedUser) do
    root :to => "user_objects"
  end
  root 'pages#index'

Then I have this file in lib/authenticated_user.rb … 然后我在lib / authenticated_user.rb中有这个文件……

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

Unfortunately, when I'm logged in, and I access http://localhost:3000/ , I get this error 不幸的是,当我登录并访问http:// localhost:3000 /时 ,出现此错误

NameError

uninitialized constant AuthenticatedUser

Any idea how I can redirect the user to the suggested page if someone is logged in? 知道有人登录后如何将用户重定向到建议的页面吗?

Edit: My config/routes.rb file is as follows ... 编辑:我的config / routes.rb文件如下...

  resources :user_objects, except: :update do
    member do
      patch :create
      put :create
    end
    get :find_by_user_object_and_day, on: :collection
    get :find_totals, on: :collection
  end

  get "users/edit" => "users#edit"
  resources :users

  root 'pages#index'

  get '/auth/:provider/callback', to: 'sessions#create'
  get '/logout', to: 'sessions#destroy'
  delete '/logout', to: 'sessions#destroy'

In the controller action for whatever root is, you can just say: 在控制器操作中,无论根是什么,您都可以说:

if current_user
  redirect_to user_objects_path #look up the rails helper    
end

The documentation on constraints recommends putting custom constraint classes to lib/constraints . 有关constraints文档建议将自定义约束类放入lib/constraints

Anyway, for the class to be recognized in routes you should have it autoloaded . 无论如何,要在routes识别该类, 应将其自动加载 Add the directory where the constraint resides to the list of autoloaded directories in application.rb : 将约束所在的目录添加到application.rb中自动加载的目录列表中:

# config/application.rb
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W[...
                           #{config.root}/lib/constraints]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM