[英]Rails - has_one and belongs_to for association
I have these two tables: 我有这两个表:
accounts
- user_id
users
- account_id
Many users can belong to an account and an account can have exactly one owner with full permissions. 许多用户可以属于一个帐户,一个帐户可以只有一个拥有完全权限的所有者。 If a user owns an account, the two should reference each other.
如果用户拥有一个帐户,则两者应相互引用。 I'm trying to figure out how to set up this association.
我正在尝试弄清楚如何建立此关联。 Here's what I have:
这是我所拥有的:
class Account < AR::Base
has_many :users
has_one :owner, class_name: 'User', foreign_key: :user_id
This seems right to me, but the User class is definitely not: 这对我来说似乎是正确的,但是User类绝对不是:
class User < AR::Base
belongs_to :account
has_one :account
An object can't belong to and have one at the same time. 一个对象不能同时属于一个对象。 How should I set up my User class?
我应该如何设置用户类?
Following should work I think: 我认为以下应该起作用:
class Account < AR::Base
has_many :users
belongs_to :owner, class_name: 'User', foreign_key: :user_id
class User < AR::Base
belongs_to :account
has_one :account, inverse_of: :owner
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.