简体   繁体   English

为非管理员用户(属性)设置不同的路由页面(在Rails上的ruby上设计gem)

[英]Set different route page for non admin users (attribute) (devise gem on ruby on rails)

Im currently learning ROR and have bumped into a small issue regarding different root pages depending on the user type. 我目前正在学习ROR,并根据用户类型遇到了有关不同根页面的小问题。 In my user model i have an attribute for admin which is either true or false depending on the user. 在我的用户模型中,我有一个admin属性,取决于用户,该属性为true或false。

Please see my routes file below, currently all users aways go to 'houses#index', even if they have admin set as false. 请在下面查看我的路线文件,即使所有管理员都设置为false,当前所有用户都将转到“ houses#index”。

I cannot see where i am going wrong in my routes file. 我在路线文件中看不到哪里出错了。

Is there anyway to add a condition for attribute admin on authenicated user in my routes file? 无论如何,在我的路由文件中是否为经过身份验证的用户添加属性admin的条件?

Routes.rb 的routes.rb

Rails.application.routes.draw do
  devise_for :user
  get 'welcome/index'
  resources :houses
  resources :tenants
  resources :requests

  authenticated :user do
    root 'houses#index', as: "authenticated_root"
  end

  authenticated :user, {admin:'false'} do
    root 'requests#index', as: "authenticated_root1"
  end

  root 'welcome#index'
end

model\\User.rb 模型\\ User.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :houses
  has_many :tenants
  has_many :requests

  def admin?
    admin
  end

end

Thanks. 谢谢。

You should use after_sign_in_path_for devise's method in your application_controller. 您应该在application_controller中使用after_sign_in_path_for设计方法。

https://github.com/plataformatec/devise/wiki/How-To:-redirect-to-a-specific-page-on-successful-sign-in https://github.com/plataformatec/devise/wiki/How-To:-redirect-to-a-specific-page-on-successful-sign-in

For instance: 例如:

def after_sign_in_path_for(resource)
  stored_location_for(resource) || (resource.admin? ? admin_dashboard_url : user_dashboard_url(resource))
end

(Please note that resource is like an alias for the user instance. By default it's the first devise role declared in your routes as said here: https://stackoverflow.com/a/40825885/10347572 ) (请注意,资源就像用户实例的别名。默认情况下,它是您的路由中声明的第一个devise角色,如下所示: https : //stackoverflow.com/a/40825885/10347572

For all other requests, if you're not using Cancan, create a new method (pretty similar to the one above) to redirect the user according to his type (but if a user wants to access to an admin page, you should raise a 404 and not just a root redirection) 对于所有其他请求,如果您不使用Cancan,请创建一个新方法(与上面的方法非常相似)以根据用户的类型重定向用户(但如果用户要访问管理页面,则应提出一个404,而不仅仅是根重定向)

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

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