我试着这样做。
Devise single table inheritance
之后,我使用/ admin / sign_in登录,在控制器中创建断点。我发现current_user总是返回nil,user_signed_in?总是假的。
有人能帮助我吗?
# model
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
#attr_accessible :name, :email, :password, :password_confirmation
end
class Customer < User
end
class Restaurant < User
end
class Admin < Customer
end
class Staff < Customer
end
# application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
# Devise helper configuration
helper_method :current_admin, :current_restaurant, :current_staff,
:require_admin!, :require_restaurant!, :require_staff!
include DeviseModule
end
# concern/devise_module.rb
module DeviseModule
def account_url
return new_user_session_url unless user_signed_in?
case current_user.class.name
when "Admin"
admins_root_url
when "Staff"
staffs_root_url
when "Restaurant"
restaurants_root_url
else
root_url
end if user_signed_in?
end
def after_sign_in_path_for(resource)
stored_location_for(resource) || account_url
end
private
def current_admin
@current_admin ||= current_user if user_signed_in? and current_user.class.name == "Admin"
end
def current_staff
@current_staff ||= current_user if user_signed_in? and current_user.class.name == "Staff"
end
def current_restaurant
@current_restaurant ||= current_user if user_signed_in? and current_user.class.name == "Restaurant"
end
def admin_logged_in?
@admin_logged_in ||= user_signed_in? and current_admin
end
def staff_logged_in?
@Buyer_logged_in ||= user_signed_in? and current_staff
end
def restaurant_logged_in?
@seller_logged_in ||= user_signed_in? and current_restaurant
end
def require_admin
require_user_type(:admin)
end
def require_staff
require_user_type(:staff)
end
def require_restaurant
require_user_type(:restaurant)
end
def require_user_type(user_type)
if (user_type == :admin and !admin_logged_in?) or
(user_type == :staff and !staff_logged_in?) or
(user_type == :restaurant and !restaurant_logged_in?)
redirect_to root_path, status: 301, notice: "You must be logged in a#{'n' if user_type == :admin} #{user_type} to access this content"
return false
end
end
end
# router.rb
Rails.application.routes.draw do
devise_for :users
devise_for :admins, :skip => [:registrations]
devise_for :restaurants
devise_for :staffs
scope :module => :home do
scope :orders do
get "/", :to => "order#index"
get "/checkout", :to => "order#checkout"
post "/checkout", :to => "order#create_an_order", :as => "order_checkout"
end
root :to => "home#index"
end
namespace :admins do
resources :restaurant
root :to => "restaurant#index"
end
namespace :staffs do
root :to => "staff#index"
end
namespace :restaurants do
root :to => "retaurant#index"
end
end