使用Devise管理用户管理

Tim*_*son 10 ruby-on-rails devise ruby-on-rails-3

我是第一次尝试Devise.我想做的其中一件事是为管理员用户提供创建,查找和编辑用户的界面.这是我可能出错的地方.

我创建了一个PeopleController类,它继承自ApplicationController,它列出了人员并提供了创建和更新用户的方法和视图.除了一个例外,一切正常.当管理员用户更新他们自己的记录时,会话被清除,他们必须在保存后再次登录.

在这个应用程序中,我没有使用可注册模块.只有管​​理员用户才能创建新用户.设计用户管理工具的正确方法是什么.创建我自己的控制器似乎是错误的选择.

在此先感谢您的帮助.

Tim*_*son 8

非常感谢你的帮助.这基本上就是我在做的事情.我发现了一个线索,帮助我解决用户会话在这个wiki中编辑自己的记录时被清除的问题:

https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-account-without-providing-a-password

这是我需要的路线:

sign_in resource_name, resource, :bypass => true
Run Code Online (Sandbox Code Playgroud)

这个方法位于Devise :: Controllers :: Helpers中,所以我在我的控制器中这样做了.

class PeopleController < ApplicationController
   include Devise::Controllers::Helpers
Run Code Online (Sandbox Code Playgroud)

然后在我的update方法中,只有当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
Run Code Online (Sandbox Code Playgroud)

现在,如果当前用户编辑自己的记录,则会话在保存后将恢复.

再次感谢您的回复.


Dav*_*vid 6

这就是我在其中一个应用中管理用户的方式.我只User生成了一个类

rails g devise User
Run Code Online (Sandbox Code Playgroud)

role在这个迁移中添加了一个列:

class AddRoleToUser < ActiveRecord::Migration
  def change
    add_column :users, :role, :string, :default => "client"
  end
end
Run Code Online (Sandbox Code Playgroud)

和我的User模特:

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
Run Code Online (Sandbox Code Playgroud)

然后要创建新用户,您需要做的就是在控制器(甚至可能是子类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
Run Code Online (Sandbox Code Playgroud)

  • 我也使用CanCan,但我仍然使用单独的角色模型.查看Ryan Bates制作的精彩维基页面:https://github.com/ryanb/cancan/wiki/Separate-Role-Model (3认同)