Need a hand with associations
I have a users model, and an accounts model. Basically I would like to have...
- An account has one owner
- An account can have many users
- Users can only be a member of one account.
Does the following look right?
User.rb
class User < ApplicationRecord
has_many :accounts, foreign_key: :owner_id
end
Account.rb
class Account < ApplicationRecord
belongs_to :owner, class_name: :User, foreign_key: :owner_id
has_many :users
end
Just a quick update, after a little light reading this evening i think this maybe correct. It seems to work ok. If anyone notices something thats wrong please let me know :) thanks.
User.rb
class User < ApplicationRecord
belongs_to :account
end
Account.rb
class Account < ApplicationRecord
has_one :owner, class_name: :User, foreign_key: :owner_id
has_many :users
end
hi Daniel,
yeah a user can be the owner and be assigned to the account.
the updated code seems to work, but im all for finding out better ways to get things done.
This looks correct, but I have to express that having these names with very similar meanings is confusing: member, account, user. I'm struggling to imagine a use case for this setup. :)
Thanks Ivan,
A user is a user, they then need an account (for a business) which other users can be assigned to. This is where a user can be a member of an account. I understand the confusion.
later i can add in subscriptions to the mix to expand the app more.