1

使用这个问题和答案(将 Account 和 User 表与 Devise 一起使用)我已经成功地为我的应用程序设置了注册用户同时创建帐户的能力。目前,我有两种模型:用户和帐户。在用户模型中,我有一个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 
4

1 回答 1

3

如果您只想强制第一个用户成为管理员,请尝试以下操作:

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

它只会运行一次 - 在首次创建帐户时。我还建议验证帐户中有一些用户。

于 2012-09-13T05:00:33.773 回答