簡體   English   中英

如何使用devise gem維護管理員和用戶?(第4條)

[英]How to maintain both admin and user with devise gem?(Rails 4)

我正在使用帶有devise gem的rails 4,並按照本文-“ https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-Role ”的要求,我還為admin創建了一個模型。 現在,我有管理員和用戶模型。 我如何像在application_helper中一樣獲得current_admin,這些存在:

def resource_name
 :user
end

def resource
 @resource ||= User.new
end

def devise_mapping
 @devise_mapping ||= Devise.mappings[:user]
end

請幫助維護管理員會話。 提前致謝

Devise的current_X幫助器方法定義如下:

def current_#{mapping}
        @current_#{mapping} ||= warden.authenticate(scope: :#{mapping})
      end

映射是角色類型。 *

因此,您應該能夠使用以下命令訪問當前管理員:

current_admin

如果這不起作用,我建議您檢查一下以確保已在Admin模型上正確實例化了設計,如下所示:

class Admin < ActiveRecord::Base
    devise :database_authenticatable # additional attributes, i.e. :trackable, :lockable 
end

*來源: https : //github.com/plataformatec/devise/blob/master/lib/devise/controllers/helpers.rb的第106行


如果您繼續遇到此問題,則可能值得重新考慮是否需要使用不同的模型將管理員和用戶分開,而不是通過向用戶模型添加管理屬性來簡化模型和實現。


編輯:

為了讓您了解在單個用戶表中查詢管理用戶與有兩個表之間的性能差異可忽略不計,我為MySQL數據庫設置了種子(在XAMPP for OSX上運行,因此絕不進行任何優化) )具有1000條用戶記錄,其中只有2位用戶將'isAdmin'設置為true。

使用SQL查詢(從1000個用戶中選擇管理員):

Showing rows 0 - 16 (17 total, Query took 0.0003 seconds.)

結果:

 Showing rows 0 - 1 (2 total, Query took 0.0004 seconds.) 


使用SQL查詢(從Admin表中選擇Admins):

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
       t.string :username
       t.boolean :isAdmin, default: false
        ...
    end
  end
end

結果:

users = User.where(:isAdmin => false)

這絕不是一個令人難以置信的徹底的例子-僅僅是為了提供一個關於這樣使用時的最小差異的想法。 Active Record可能會稍微快一些/慢一些,但是我無法想象它與上面的結果會有太大的不同。

就個人而言,我發現向用戶模型添加“ isAdmin”(或類似屬性)更容易,如下所示:

活動記錄遷移(db \\ migrate \\ TIMESTAMP_create_users.rb)

admins = User.where(:isAdmin => true)

然后像這樣在用戶和管理員之間進行過濾:

用戶(管理員除外)

 users = User.where(:isAdmin => false) 

全部用戶

 allUsers = User.all 

僅限管理員

 admins = User.where(:isAdmin => true) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM