我有Account
和User
的简单设置:
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
拥有“所有者”(对该帐户拥有完全权限的用户)。我能想到的选择:
account_owner
的用户上添加一个布尔字段? (对我来说不合适)accounts
的{{1}}表上添加一个字段,从而产生一种鸡蛋问题。答案 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'