我是rails新手,正在开发我的第二个rails应用程序。
应用程序将为用户提供不同的角色,但某些用户将具有多个角色。
网站的每个用户都是艺术家。一些用户将扮演主持人的角色。
我该如何构造这个?在我使用过的一些php应用程序中,只有一个用户,然后是is_admin等的数据库列。但是我查看了rails应用程序的源代码,并看到了用户和管理员等的单独模型,尽管我不知道为什么。
那么,我是否应该有一个具有角色属性的单用户模型,该模型可以是版主,然后在我的视图、路线等中将用户称为“艺术家”?
或者我应该有一个用户模型,一个继承自它的版主模型,和一个属于用户的艺术家模型?
我真的很困惑。
最佳答案
你可以找宝石设计和坎坎。这一对真的是强大的组合。这使得两个模型成为用户和角色。在角色中,您可以创建新角色,而不必为它们创建新模型。尽管它创建了模型功能,但在这里您可以定义角色的访问规则。
手册:
http://www.tonyamoyal.com/2010/07/28/rails-authentication-with-devise-and-cancan-customizing-devise-controllers/
在这里你可以找到Devise和Cancan的资源和维基:
https://github.com/plataformatec/devise
https://github.com/ryanb/cancan
我的模特看起来是这样的:
RB
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end
用户地址
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
职权范围
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
在控制器中,只能添加这两行:
class YourController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource
...
end