繁体   English   中英

设计:创建管理员用户和帐户

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM