[英]Admin user administration with Devise
我第一次尝试 Devise。 我想做的一件事是为管理员用户提供一个界面来创建、查找和编辑用户。 这就是我可能出错的地方。
我创建了一个 PeopleController class,它继承自 ApplicationController,它列出人员并提供用于创建和更新用户的方法和视图。 一切正常,只有一个例外。 当管理员用户更新自己的记录时,session 被清除,保存后必须重新登录。
在这个应用程序中,我没有使用可注册模块。 只有管理员用户可以创建新用户。 devise提供用户管理工具的正确方法是什么。 创建我自己的 controller 似乎是错误的道路。
在此先感谢您的帮助。
非常感谢你的帮助。 这基本上正是我正在做的事情。 我发现了一条线索,帮助我解决了用户在此 wiki 中编辑自己的记录时清除用户的 session 的问题:
这是我需要的行:
sign_in resource_name, resource, :bypass => true
此方法位于 Devise::Controllers::Helpers 中,所以我在 controller 中执行此操作。
class PeopleController < ApplicationController
include Devise::Controllers::Helpers
然后在我的更新方法中,我只在 current_user.id 等于正在编辑的 id 时才调用它:
def update
@person = User.find(params[:id])
if @person.update_attributes(params[:user])
sign_in @person, :bypass => true if current_user.id == @person.id
redirect_to person_path(@person), :notice => "Successfully updated user."
else
render :action => 'edit'
end
end
现在如果当前用户编辑自己的记录,session 保存后会恢复。
再次感谢您的回复。
这就是我在我的一个应用程序中管理用户的方式。 我只有一个User
class 生成
rails g devise User
我在此迁移中添加了一个role
列:
class AddRoleToUser < ActiveRecord::Migration
def change
add_column :users, :role, :string, :default => "client"
end
end
和我的User
model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
def admin?
self.role == "admin"
end
end
然后要创建新用户,您所要做的就是在 controller (甚至可能是子类Devise::RegistrationsController
)中提供一个自定义方法,如下所示:
# some_controller.rb
def custom_create_user
if current_user.admin?
User.create(:email => params[:email], password => params[:password])
redirect_to(some_path, :notice => 'sucessfully updated user.')
else
redirect_to(some_other_path, :notice => 'You are not authorized to do this.')
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.