使用 Devise Rails 的用户和管理员之间的唯一 ID [英] Unique IDs between Users and Admins with Devise Rails

查看:17
本文介绍了使用 Devise Rails 的用户和管理员之间的唯一 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经安装了 Devise 并使用本教程中的选项 1 创建了用户和管理员 https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-role

I have installed Devise and created Users and also Admins using Option 1 from this tutorial https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-role

现在我需要一点帮助.添加管理员时,它会创建一个不同的表,并且管理员和普通用户可能具有相同的 ID.

Now I need a little help. When adding the Admins it creates a different table, and the potential arises that the admins and regular users could have the same ID's.

那么我究竟是如何从用户和管理员那里获取信息的呢?比如说我想显示所有用户?我必须先遍历 users 表然后再遍历 admins 表吗?

So how exactly do I got about grabbing information from users and admins? Say for example I want to display all users? Do I have to traverse the users table and then the admins table?

或者如果我正在显示一个帖子.我如何知道要查找哪个表来获取用户或管理员信息?

Or if I am displaying a post. How will I know which table to look for to get the user or admin info?

我知道我可以向用户表中添加一个角色列,但我想避免这种情况.

I know I can just add a role column to the users table but I wanted to avoid this.

我希望这是有道理的哈哈

I hope this makes sense haha

推荐答案

我强烈建议使用单表继承 (STI).您可以通过在 users 表中添加名为 type 的列和 string 数据类型并创建一个 admin 来执行 STI> 模型以及 normal_user 模型,这两个模型都将从 devise gem 的 user 模型继承.

I highly recommend using the Single Table Inheritance (STI). You could do the STI by adding a column named type with a string datatype in the users table and create an admin model as well as a normal_user model both models will inherit from the user model of the devise gem.

class NormalUser < User
end

class Admin < User
end

类型列是一个保留字,它将根据您创建的用户类型保存一个 NormalUserAdmin 值.

The type column is a reserved word which will hold a value either NormalUser or Admin according to the user type you created.

要创建管理员使用 Admin.create(...) 并创建普通用户使用 NormalUser.create(...) 其中点是AdminNormalUser

To create an admin use Admin.create(...) and to create a normal user use NormalUser.create(...) where the dots are the attributes of the Admin and the NormalUser

这篇关于使用 Devise Rails 的用户和管理员之间的唯一 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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