Many-to-many Users and groups, but groups have owners

many-to-many, ruby-on-rails

Solution

You can set it up a couple of ways:

1) Use a join model and place a flag on the join model that specifies that the group member is an owner.

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, through: :memberships
  attr_accessible :name, :description, :isPublic, :tag_list, :owner
end

class Membership < ActiveRecord::Base
  belongs_to :group
  belongs_to :user

  #this table has a flag called owner and thus a method called owner?
end

class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, through: :memberships
  attr_accessible :name, :description, :owner_id
end

2) Keep your existing HABTM and add another join model for tracking ownership.

class Group < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_many :group_ownerships
  has_many :owners, through: :group_owernships, class_name: "User"
  attr_accessible :name, :description, :isPublic, :tag_list, :owner
end

class GroupOwnership < ActiveRecord::Base
  belongs_to :group
  belongs_to :user
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :groups
  has_many :group_ownerships
  has_many :owned_groups, through: :group_owernships, class_name: "Group"
  attr_accessible :name, :description, :owner_id
end

Problem

I'm having trouble trying to understand/wrap my brain around this. I'm trying to create a relationship that allows this: - user can belong to many groups - group can have many users - a group has an owner which is a user - the group ownership can be transferable I've got the many-to-many relationship set up, but I can't seem to understand how to set up the ownership functionality. here is what i have so far in my models: ``` class Group < ActiveRecord::Base has_and_belongs_to_many :users attr_accessible :name, :description, :isPublic, :tag_list, :owner end class User < ActiveRecord::Base has_and_belongs_to_many :groups attr_accessible :name, :description, :owner_id end ``` Any help would be greatly appreciated!!

Original source