与所有者一起设计用户/帐户模型

时间:2013-02-03 04:39:39

标签: ruby-on-rails database-design

我有AccountUser的简单设置:

class Account < ActiveRecord::Base
  has_many :users
end

accounts
--------
id
name
...

class User < ActiveRecord::Base
  belongs_to :account
end

users
-----
id
account_id
username
...

现在,我如何设计Account拥有“所有者”(对该帐户拥有完全权限的用户)。我能想到的选择:

  1. 在名为account_owner的用户上添加一个布尔字段? (对我来说不合适)
  2. 在名为accounts的{​​{1}}表上添加一个字段,从而产生一种鸡蛋问题。
  3. 别的什么?角色?

2 个答案:

答案 0 :(得分:1)

这样的事情会起作用吗?您需要向owner_id添加Account外键。

class Account < ActiveRecord::Base
  belongs_to :owner, class_name: "User"
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :account
end

# Somewhere in your code...

account = Account.create(name: "Account 1")
owner   = User.create(username: "tom")

account.users << owner
account.users << User.create(username: "sarah")
account.owner = owner
account.save

答案 1 :(得分:0)

如果帐户可能有多个所有者,则可以向用户添加角色列。

@user.account == @account && @user.role == 'admin'
相关问题