【问题标题】:Devise: Creating Admins Users and Accounts设计:创建管理员用户和帐户
【发布时间】:2012-09-11 03:49:10
【问题描述】:

使用这个问题和答案 (Use both Account and User tables with 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 

【问题讨论】:

  • Taryn:感谢您的回复。我在下面尝试了迈克尔的建议并收到了一条错误消息。从那时起,我尝试了许多组合来启动服务器——其中一些是成功的——但它们都没有将 true 作为第一个用户添加到 admin 字段——我尝试的组合包括 validates :管理员, :in => {:in => [true]}, :if => :first?

标签: ruby-on-rails devise


【解决方案1】:

如果您只想强制第一个用户成为管理员,那么试试这个:

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

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

【讨论】:

  • Taryn:感谢您的回复,代码(您可能知道)就像一个魅力。这就是我一直在寻找的东西,虽然我昨晚有一些工作要做,但它并不像你发布的那样干净和令人愉快。我要处理的下一个任务是让管理员可以创建用户,并且为这些用户分配与管理员相同的帐号。祝我好运,再次感谢您的帮助。
最近更新 更多