Sco*_*ott 6 ruby ruby-on-rails
我是rails的新手,我正在开发第二个rails应用程序.
该应用程序将为用户提供不同的角色,但某些用户将拥有多个角色.
该网站的每个用户都是艺术家.一些用户将扮演主持人的角色.
我该如何构建这个?在我使用过的一些PHP应用程序中,只有一个用户,然后是is_admin的数据库列,等等.但我查看了rails应用程序的源代码,并看到了用户和管理员等的单独模型,尽管我我不确定为什么.
那么,我应该有一个带有角色属性的用户模型,可以是主持人,然后在我的视图,路线等中调用用户"艺术家"吗?
或者我应该有一个User模型,一个继承自它的Moderator模型,以及一个belongs_to User的Artist模型?
我真的很困惑.
你可以寻找宝石Devise和CanCan.这对真是强大的组合.这使得两个模型User和Role.在角色中,您可以创建新角色,而无需为其创建新模型.虽然它创建了模型能力,但您可以在此处定义角色的访问规则.
手册:http: //www.tonyamoyal.com/2010/07/28/rails-authentication-with-devise-and-cancan-customizing-devise-controllers/
在这里你可以找到Devise和CanCan的来源和wikies:
https://github.com/plataformatec/devise
https://github.com/ryanb/cancan
我的模型看起来像这样:
Role.rb
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end
Run Code Online (Sandbox Code Playgroud)
User.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
Run Code Online (Sandbox Code Playgroud)
Ability.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
Run Code Online (Sandbox Code Playgroud)
在控制器中,您必须只添加以下两行:
class YourController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource
...
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1852 次 |
| 最近记录: |