[英]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.