问题
I used RailsApps rails-composer to create a rails-devise-pundit starter application. I am still a little new to ruby on rails and newer to devise, pundit and rails 4.
I was looking at the code to learn how it works. There are many places in controllers and in policy classes where user.admin? is called. But I can't find the admin? method. I would expect it to be in the User model but it isn't there. Here's the user class:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
enum role: [:user, :vip, :admin]
after_initialize :set_default_role, :if => :new_record?
def set_default_role
self.role ||= :user
end
end
Used in part of users_controller.rb:
def show
@user = User.find(params[:id])
unless current_user.admin?
unless @user == current_user
redirect_to root_path, :alert => "Access denied."
end
end
end
Does pundit or devise create this method somehow? I've seen it used in the pundit documentation but it just uses it as an example. It doesn't say the method needs to be created or that it handles it. Is it somehow using the role enum which has :admin as a possible value? If anyone can explain how this works, I'd appreciate it.
I'm planning to add in use of the rolify gem soon to handle roles instead of the role enum in the user class. Maybe I'll want to make role names that are completely different for some reason. I want to make sure I understand how to keep everything working. Thanks.
回答1:
Roles are defined in the app/models/User.rb file (the User
model).
class User < ActiveRecord::Base
.
.
.
enum role: [:user, :vip, :admin]
after_initialize :set_default_role, :if => :new_record?
def set_default_role
self.role ||= :user
end
end
The application uses the ActiveRecord enum
method to manage roles. ActiveRecord provides convenient methods to query the role attribute:
user.admin! # sets the role to "admin"
user.admin? # => true
user.role # => "admin"
See documentation for ActiveRecord::Enum for details. The ActiveRecord enum
method is new in Rails 4.1.
I've updated the README for the rails-devise-pundit application to include this information. It's also covered in my Rails Pundit Tutorial.
回答2:
It is an attribute of the User model. Same as first_name
or last_name
, there is a field called admin
which is a boolean.
来源:https://stackoverflow.com/questions/22213152/where-is-user-admin-defined-in-rails-devise-pundit-starter-app