用户的 Rails 模型结构 [英] Rails model structure for users
问题描述
我是 Rails 的新手,我正在开发我的第二个 Rails 应用.
I'm new to rails, and I'm working on my second rails app.
该应用将为用户分配不同的角色,但有些用户将拥有多个角色.
The app will have different roles for users, but some users will have multiple roles.
该网站的每个用户都将成为艺术家.一些用户将担任版主的角色.
Every user of the site will be an Artist. Some users will have the role of a moderator.
我将如何构建它?在我使用的一些 PHP 应用程序中,只有一个用户,然后是 is_admin 等的数据库列.但我查看了 rails 应用程序的源代码,并看到了用户和管理员等的单独模型,尽管我不知道为什么.
How would I structure this? In some PHP apps I've used, there is only one user, and then a database column for is_admin, etc. But I've looked at the source for rails apps and have seen separate models for User and Admin, etc. although I'm not sure why.
那么,我是否应该有一个带有角色属性的 User 模型,它可以是 Moderator,然后在我的视图、路由等中将 Users 称为艺术家"?
So, should I have a single User model with a role attribute, which could be Moderator, and then just call Users "Artists" in my views, routes, etc.?
或者我应该有一个 User 模型、一个继承自它的 Moderator 模型和一个属于 User 的 Artist 模型?
Or should I have a User model, a Moderator model which inherits from it, and an Artist model which belongs_to User?
我真的很困惑.
推荐答案
您可以寻找 Devise 和 CanCan 的宝石.这对组合真的很强大.这使得两个模型用户和角色.在角色中,您可以创建新角色,而无需为其创建新模型.虽然创建了模型能力,但是这里可以定义角色的访问规则.
You can look for gems Devise and CanCan. This pair is really powerful combination. This makes two models User and Role. In Role you can create new roles, without creating new models for them. Although it creates model Ability, here you can define access rules for roles.
您可以在此处找到 Devise 和 CanCan 的来源和维基:
Here you can find Devise's and CanCan's sources and wikies:
https://github.com/plataformatec/devise
https://github.com/ryanb/cancan
我的模型如下所示:
角色.rb
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end
用户.rb
class User < ActiveRecord::Base
has_many :accounts
has_and_belongs_to_many :roles
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :username, :password, :password_confirmation, :remember_me, :role_ids
def role?(role)
return !!self.roles.find_by_name(role.to_s.camelize)
end
end
能力.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
if user.role? :administrator
can :manage, :all
elsif user.role? :operator
can :read, Account
can :read, Server
elsif user.role? :customer
can :manage, Account
can :read, Server
end
end
end
在控制器中你必须只添加这两行:
In the controller you must add only this two lines:
class YourController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource
...
end
这篇关于用户的 Rails 模型结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!