0

我已经按照这个 tut http://railsapps.github.com/tutorial-rails-bootstrap-devise-cancan.html我想做这样的事情:

before_filter :authenticate_user!
before_filter :authenticate_VIP!
before_filter :authenticate_admin!
before_filter :authenticate_somerole!

我有表:角色、用户、user_roles,我不想创建另一个表(rails g 设计 VIP 创建另一个表)。

我想要方法authenticate_ROLE。这该怎么做 ?

4

1 回答 1

3

我有三个表,Users、Roles 和 RoleRelationships(或 role_users,由你决定)

这是我的角色表:

class Role < ActiveRecord::Base
  attr_accessible :name
  has_many :role_relationships
  has_many :users, through: :role_relationships
end

角色表将具有name角色列,例如:“admin”、“teacher”、“vip”(如您所愿)。

这是用户表:

class User < ActiveRecord::Base
  devise ...
  has_many :role_relationships
  has_many :roles, through: :role_relationships
end

和我的 RoleRelationship 表:

class RoleRelationship < ActiveRecord::Base
  attr_protected :role_id, :user_id

  belongs_to :user
  belongs_to :role
end

我设置了我的应用程序一个用户可以有很多角色,你可以设置自己的方式。所以,我有一个role?(role)方法user.rb,如下所示:

def role?(role)
  return role == RoleRelationship.find_by_user_id(self.id).role.name
end

然后在我的abilities文件中,我定义了用户的能力:

def initialize(user)

  user ||= User.new # guest user

  if user.role? "teacher"
        can :read, Course
        can :manage, Topic, user_id: user.id
        can :create, Topic
  else  user.role? "admin"
        can :manage, Course
  end

所以,teacher只会读取Course,并且admin可以 CRUD Course。为此,我load_and_authorize_resource在 CoursesController 中使用方法:

class CoursesController < ApplicationController

  load_and_authorize_resource

  before_filter :authenticate_user!
  ...
end

最后,在我看来,我使用了这样的代码:

<% if can? manage, @course %>
   Only admin can work, see what happen here.
<% end %>

因此,如您所见,teacher他们只能阅读课程,因此他们无法看到或执行管理员可以做的事情,在这种情况下,是创建课程或编辑课程。
这是我在我的在线测试应用程序中构建的,您可以参考并为您的应用程序执行相同的操作。

于 2012-11-04T20:10:12.830 回答