Reputation: 380
I am using rails 4 with devise gem and following this article -"https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-Role", I created a model for admin also. Now I have both admin and user model. How can I get the current_admin as in application_helper, these are present:-
def resource_name
:user
end
def resource
@resource ||= User.new
end
def devise_mapping
@devise_mapping ||= Devise.mappings[:user]
end
Please help to main a admin session. Thanks in advance
Upvotes: 3
Views: 953
Reputation: 6042
Devise's current_X helper methods are defined like this:
def current_#{mapping}
@current_#{mapping} ||= warden.authenticate(scope: :#{mapping})
end
where mapping is the role type. *
As such, you should be able to access the current admin using:
current_admin
If this doesn't work, I would recommend checking to make sure that devise has been properly instanciated on the Admin model, as follows:
class Admin < ActiveRecord::Base
devise :database_authenticatable # additional attributes, i.e. :trackable, :lockable
end
*Source: Line 106 of https://github.com/plataformatec/devise/blob/master/lib/devise/controllers/helpers.rb
SELECT * FROM `users` WHERE isAdmin = 1
Result:
Showing rows 0 - 1 (2 total, Query took 0.0004 seconds.)
Query using SQL (Selecting Admins from an Admin table):
SELECT * FROM `administrators`
Result:
Showing rows 0 - 16 (17 total, Query took 0.0003 seconds.)
This is by no means an incredibly thorough example - it was just to provide an idea as to the minimal difference when used like this. Active Record may be slightly quicker/slower, but I can't imagine it would be too different to the results above.
Personally, I find it easier to add an 'isAdmin' (or similar) attribute to my users model, like this:
Active Record migration (db\migrate\TIMESTAMP_create_users.rb)
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.boolean :isAdmin, default: false
...
end
end
end
and then filter between Users and Administrators like so:
Users, except Admins
users = User.where(:isAdmin => false)
All users
allUsers = User.all
Admins only
admins = User.where(:isAdmin => true)
Upvotes: 4