All threads / Need a hand with associations

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

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

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

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.

Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.