Ask A Question

Notifications

You’re not receiving notifications from this thread.

Need a hand with associations

Alan Reid asked in Rails

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
Reply

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
Reply

Can a user be both a regular user and the ower of an account at the same time?

Reply

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.

Reply

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. :)

Reply

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.

Reply

Thanks for explaining.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,563+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.