Reputation: 4005
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:
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?
Upvotes: 1
Views: 297
Reputation: 13077
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
Upvotes: 2