Canard gem - 我应该以编程方式创建管理员用户?

时间:2013-11-22 16:29:09

标签: ruby-on-rails ruby activerecord cancan

我正在使用Canard gem(CanCan + RoleModel)在Ruby on Rails上进行身份验证,但我在制作初始用户管理员时遇到了一些问题。帐户有用户。创建帐户时,会有拥有结算详细信息的所有者用户。我希望该所有者拥有:admin角色。

class SomewhereElseInSystem
  ...
  account = Account.register(hash) # Company Admin submits form with
                                   # details of account, owning user,
                                   # and a load more objects we don't
                                   # show here.
end

class Account < ActiveRecord::Base
  has_many :users, dependent: :destroy, include: [:profile]
  has_one :owner, class_name: 'User', conditions: { owner: true }
  accepts_nested_attributes_for :owner

  def self.register(details)
    ...
    hash = { name:   details[:client_name],
             domain: details[:subdomain],
             plan:   details[:plan],
             owner_attributes: {
               name:                  details[:owner_name],
               password:              details[:owner_password],
               password_confirmation: details[:owner_password],
               email:                 details[:owner_email] } } 
    account = Account.create hash
    ...
  end
end

class User < ActiveRecord::Base
  belongs_to :account
  acts_as_user roles: [:saas_admin, :admin, :manager]

  # owner is a boolean DB field

  before_validation :owners_are_admins

  protected

  def owners_are_admins
    return unless owner
    self.roles << :admin
  end
end

但是,我发现当我创建帐户时,关联所有者不是管理员,并且没有设置角色。我已经尝试了上面的几个变种,并且我确信我遗漏了一些基本的东西。帮助

更新 如果我进入控制台,我可以通过示波器看到4个非管理员而不是1个管理员和3个非管理员,但是通过管理员可以获得不同的答案。和实际的领域。

[46] subscriptions »  account.users.count
   (0.5ms)  SELECT COUNT(*) FROM "users" WHERE "users"."account_id" = 1
=> 4
[47] subscriptions »  account.users.admins.count
   (0.4ms)  SELECT COUNT(*) FROM "users" WHERE "users"."account_id" = 1 AND ("users"."roles_mask" & 2 > 0)
[48] subscriptions »  account.users.non_admins.count
[48] subscriptions »  account.users.non_admins.count
   (0.6ms)  SELECT COUNT(*) FROM "users" WHERE "users"."account_id" = 1 AND ("users"."roles_mask" & 2 = 0 or "users"."roles_mask" is null)
=> 4
[49] subscriptions »  account.users.map(&:admin?)
=> [
  [0] false,
  [1] false,
  [2] false,
  [3] true
]
[51] subscriptions »  account.users.select{ |user| user.roles_mask & 2 > 0 }.count 0;34# Same as query above
=> 1

但更好的是,如果我这样做

account.users.admins # 0
owner = account.owner
owner.roles << :admin # Should be a no-op
owner.save!
account.user.admins # 1!

显然我的回调不是等同于&lt;&lt;毕竟在控制台中。我不明白。

0 个答案:

没有答案