[英]Devise: Creating Admins Users and Accounts
使用此問題和答案(同時使用帳戶和用戶表格設計 )我已成功為我的應用程序設置了注冊同時創建帳戶的用戶的能力。 目前,我有兩個模型:用戶和帳戶。 在用戶模型中,我有一個account_id
字段。
我現在正在努力使這個用戶(即創建帳戶的第一個用戶)默認為管理員。 我的用戶模型中有一個管理字段(這與ActiveAdmin一起使用,已設置為使用單個用戶模型)。
其次,我知道有多個帖子可以確定管理員用戶如何創建其他用戶(我仍然試圖與Devise一起工作),但有人可以用最簡單的方式指導我,以便其他所有用戶都被分配相同的account_id
。 我計划使用CanCan來控制管理員和非管理員在ActiveAdmin和應用程序中的訪問權限。
任何援助都將非常感激。
我目前的模特是:
帳戶模型
class Account < ActiveRecord::Base
has_many :users, :inverse_of => :account, :dependent => :destroy
accepts_nested_attributes_for :users
attr_accessible :name, :users_attributes
end
用戶模型
class User < ActiveRecord::Base
belongs_to :account, :inverse_of => :users
validates :account, :presence => true
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me
end
我的控制器是:
賬戶管理員
class AccountsController < ApplicationController
def new
@accounts = Account.new
@accounts.users.build
end
def create
@account = Account.new(params[:account])
if @account.save
flash[:success] = "Account created"
redirect_to accounts_path
else
render 'new'
end
end
end
用戶控制器
class UsersController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource # CanCan
def new
@user = User.new
end
def create
@user.skip_confirmation! # confirm immediately--don't require email confirmation
if @user.save
flash[:success] = "User added and activated."
redirect_to users_path # list of all users
else
render 'new'
end
end
end
如果你想做的就是強迫第一個用戶成為管理員,那么試試這個:
class Account < ActiveRecord::Base
after_create :make_first_user_an_admin
def make_first_user_an_admin
return true unless self.users.present?
self.users.first.update_attribute(:admin, true)
end
end
它只會運行一次 - 在首次創建帳戶時。 我還建議驗證帳戶中是否有一些用戶。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.