2010-07-08 13 views
2

我想做一個簡單的登錄,註銷,另外,不同的用戶有不同的用戶角色。 Restful認證看起來很好,而cancan對於控制用戶能力也非常好。但問題是我怎樣才能讓這兩項工作在一起。我觀看了火車,我是否是如何檢測用戶的能力?我是否需要在用戶表中添加「能力」列?謝謝你。任何在RoR上進行身份驗證的懶惰方式?

http://railscasts.com/episodes/67-restful-authentication

http://railscasts.com/episodes/192-authorization-with-cancan

+1

當然,所有你需要做的就是讓別人去做。 :) – ChaosPandion 2010-07-08 15:56:07

回答

0

我寫了一個簡單的解決方案,與慘慘過的作品,只需添加一個ROLE_ID:整數列,用戶模型:

# puts this in /lib/ 
module RolePlay 
    module PluginMethods 
    def has_roleplay(roles = {}) 
     @@roles = roles 
     @@roles_ids = roles.invert 

     def roles 
     @@roles 
     end 

     def find_by_role(role_name, *args) 
     find(:all, :conditions => { :role_id => @@roles[role_name]}, *args) 
     end 

     define_method 'role?' do |r| 
     r == @@roles_ids[role_id] 
     end 

     define_method :role do 
     @@roles_ids[role_id] 
     end 
    end 
    end 
end 

然後包括在配置這條線/initializers/roleplay.rb

ActiveRecord::Base.extend RolePlay::PluginMethods 

終於在你的用戶模型中使用它:

class User < ActiveRecord::Base 
    # ... 
    has_roleplay(:admin => 0, :teacher => 1, :student => 2) 
    # ... 
end 

現在你的模型將有2種新的方法:

@user.role?(:admin) # true if user has admin role 
@user.role # returns role name for the user 
1

看那康康舞GitHub的頁面:http://github.com/ryanb/cancan

基於望着那和RailsCast兩個,我注意到兩兩件事:

  1. 你定義的能力作爲一個單獨的模型。似乎沒有任何必要的數據庫列。
  2. 有沒有辦法讓你被迫做角色,你可以自由地做到這一點,但你會。

隨着restful_authentication,只是做正常的事情與你User模型。

最自然的方式來增加慘慘將是一個額外的列添加到您的User模式叫roleability或東西,那麼你認爲合適的定義方法。我個人可能會做一些存儲在數據庫中的數字系統,如管理員的「0」,高級用戶的「1」,低級用戶的「2」等。

這是一個幾種可能性:

# Returns true if User is an admin 
def admin? 
    self.role == 0 
end 

和:

# Returns true if User is admin and role?(:admin) is called, etc. 
def role?(to_match) 
    { 
    0 => :admin, 
    1 => :super_user, 
    2 => :user, 
    3 => :commenter, 
    }[self.role] == to_match 
end 

然後在您的Abilityinitialize方法,你可以使用某種條件語句來設置的能力,如從Railscast /自述這些內容摘要:

if user.role? :admin 
    can :manage, :all 
elsif user.role? :super_user 
    ... 
end 

或者:

if user.admin? 
    can :manage, :all 
else 
    ... 
end 
+0

因此,用戶正在調用角色列,僅用於取回安全號碼,對吧? – Tattat 2010-07-09 04:00:06

+0

角色列僅用於返回表示不同類型用戶的不同數字,因此您知道提供給他們的能力。 – Karl 2010-07-09 16:11:36

相關問題