2011-06-13 61 views
9

我正在嘗試第一次設計。我想要做的一件事是爲管理員用戶提供一個界面來創建,查找和編輯用戶。這是我可能出錯的地方。管理用戶管理與設計

我創建了一個PeopleController類,該類繼承自ApplicationController,它列出了人員並提供了用於創建和更新用戶的方法和視圖。除了一個例外,一切正常。當管理員用戶更新自己的記錄時,會話將被清除,並且在保存後必須重新登錄。

在這個應用程序中,我沒有使用可註冊模塊。只有管​​理員用戶可以創建新用戶。設計提供用戶管理工具的正確方法是什麼?創建我自己的控制器似乎是錯誤的路徑。

在此先感謝您的幫助。

回答

7

非常感謝您的幫助。這基本上就是我所做的。我發現了一個線索,幫助我解決了用戶的會話的問題被清除時,他們編輯自己的唱片在這個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 

這方法位於Devise :: Controllers :: Helpers,所以我在我的控制器中做了這個。

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 

現在,如果當前用戶編輯自己的唱片,會話恢復保存後。

再次感謝您的回覆。

6

這就是我在其中一個應用程序中管理用戶的方式。我有

rails g devise User 

只產生一個User類,我添加了一個role柱與此遷移:

class AddRoleToUser < ActiveRecord::Migration 
    def change 
    add_column :users, :role, :string, :default => "client" 
    end 
end 

和我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 

然後創建新用戶你所要做的就是在控制器中提供一個自定義方法(甚至可以是子類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 
+0

我也會推薦可能會使用一個單獨的「角色」模型,以便用戶在必要時可以擁有多個角色。可能會讓一切變得更容易。然後一個連接模型,可能被稱爲「UserRole」,它將具有user_id和role_id。 – ardavis 2011-06-14 01:55:12

+0

的確如此,儘管當我需要定義多個角色或複雜的權限時,我通常使用[cancan](https://github.com/ryanb/cancan)。 – David 2011-06-14 03:16:28

+3

我也使用CanCan,但我仍然使用單獨的角色模型。看看這個真棒維基頁面瑞安貝茨作出:https://github.com/ryanb/cancan/wiki/Separate-Role-Model – ardavis 2011-06-14 03:49:28