应用程序不识别用户作为管理员

问题描述:

我已经创建了用户角色,但是我的应用程序没有提及我的帐户是管理员。它显示了管理员的角色,但管理员也是零。应用程序不识别用户作为管理员

从铁轨控制台:

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

正如我在我的评论说,

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。

我希望它有帮助...