2013-03-15 60 views
0

我已經創建了用戶角色,但是我的應用程序沒有提及我的帳戶是管理員。它顯示了管理員的角色,但管理員也是零。應用程序不識別用戶作爲管理員

從鐵軌控制檯:

2.0.0-p0 :001 > user = User.find(13) 
    User Load (17.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 13 LIMIT 1 
=> #<User id: 13, admin: nil, role: "admin", roles_mask: nil> 
2.0.0-p0 :002 > user.roles 
=> [] 
2.0.0-p0 :003 > user.role?(:admin) 
=> false 

如果它瞭解用戶角色是admin,爲什麼還不能接受它作爲管理員,並給予該帳戶適當的權限?我需要解決這個問題,因爲我只允許管理員修改所有配置文件,然後指定普通用戶只能修改和訪問他們自己的配置文件。

user.rb:

class User < ActiveRecord::Base 
    has_secure_password 
    attr_accessible :password_confirmation, :about_me, :feet, :inches, :password, :birthday, :career, :children, :education, :email, :ethnicity, :gender, :height, :name, :password_digest, :politics, :religion, :sexuality, :user_drink, :user_smoke, :username, :zip_code 
    validates_uniqueness_of :email 
    validates_presence_of :password, :on => :create 
    before_create { generate_token(:auth_token) } 

    def send_password_reset 
    generate_token(:password_reset_token) 
    self.password_reset_sent_at = Time.zone.now 
    save! 
    UserMailer.password_reset(self).deliver 
    end 

    def generate_token(column) 
    begin 
     self[column] = SecureRandom.urlsafe_base64 
    end while User.exists?(column => self[column]) 
    end 
end 
+0

'user.roles' return'[]'是不是錯了? – Gerep 2013-03-15 14:29:22

+0

是的,我不知道爲什麼它會返回一個括號。 – pwz2000 2013-03-15 14:30:25

+0

用戶是否屬於多個角色? – 2013-03-15 14:32:26

回答

1

正如我在我的評論說,

user.role 
=> admin 

所以,你可以添加到您的application_controller是這樣的:

def admin 
    unless current_user.role == 'admin' 
    flash[:error] = "Authorisation is required to access this content." 
    redirect_to current_user 
    end 
end 

這樣,您可以阻止非管理員的用戶訪問控制器中的某些操作:

before_filter :admin, :only => [:destroy] 

這只是一個例子給你一些方向,我假設你有current_user helper。

我希望它有幫助...

相關問題