您可能会感兴趣的一些宝石:
如果您决定自己实现它,那么在某个页面中您可能想要更改内容,为此您可能想要执行以下操作:
使用迁移向用户模型添加角色:
class AddRoleToUsers < ActiveRecord::Migration
def change
add_column :users, :role, :string, default: :demo
end
end
然后在您的应用中您可以按如下方式使用它:
def index
case current_user.role
when :admin
@installations = Installation.all
when :registered
@installations = current_user.installations
else
@installations = current_user.installations.first
end
end
例如,您也可以简单地创建一个布尔值admin。
您可能还想做的是在模型中创建一些方法,以便您可以调用 current_user.admin? 或 current_user.registered? 。您可以这样做(如果您选择使用字符串来存储角色):
class User < ActiveRecord::Base
def admin?
self.role == "admin"
end
def registered?
self.role == "registered"
end
end
我看到将角色存储在字符串中的一个优点是,例如,如果您有 5 个角色,那么您就没有 4 个布尔值(就像您将 admin 存储在布尔值中一样),而只有一个字符串。从长远来看,您可能希望实际存储 role_id 而不是字符串,并拥有一个单独的 role 模型。
Jorge de Los Santos(另一个答案)指出的一个很好的替代方法是使用 enum :
class User < ActiveRecord::Base
enum role: [:demo, :admin, :registered]
end
这是一个很好的替代方案,因为它会自动添加上述方法,例如current_user.admin?,而无需对其进行硬编码。
使用您的角色,您可能想要进行一些授权(管理员可以访问特定页面,演示用户仅限于页面的子集等)。为此,您可以使用名为 cancancan 的 gem。您可以查看this railscast 以了解更多信息。另外,您可以在这里获得一些信息:How to use cancancan?。