Skip to content

Instantly share code, notes, and snippets.

@mfifth mfifth/models.rb
Last active Jan 25, 2017

Embed
What would you like to do?
class User < ActiveRecord::Base
has_many :groups, through: :group_users
end
class GroupUsers < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
class Group < ActiveRecord::Base
has_many :users, through: :group_users
end
@kwerle

This comment has been minimized.

Copy link

commented Jan 25, 2017

So you're saying:
A group belongs to a single user. That user owns the group.
In addition, a user may belong to any number of groups - but not own it?
And a Group has many users - some of which may belong to other groups or own other groups?

@kwerle

This comment has been minimized.

Copy link

commented Jan 25, 2017

Can a user own multiple groups?

@mfifth

This comment has been minimized.

Copy link
Owner Author

commented Jan 25, 2017

Um... yeah kind of.

A group belongs to a single user yes, that user owns that group.
In addition, a user may belong to any number of groups and not own them. For instance another user might add them to their own group which they would not own.

And a group can have many users.

edit: And yes a user could have multiple groups.

@kwerle

This comment has been minimized.

Copy link

commented Jan 25, 2017

class User < ActiveRecord::Base
  has_and_belongs_to_many :groups
  has_many :owned_groups, class_name: :Group
end

class Group < ActiveRecord::Base
  has_and_belongs_to_many :users
  belongs_to :owner, class_name: :User
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.