简体   繁体   中英

Modelling teams

I just wanted to get some feedback on better ways to model a team/team membership in rails.
I currently have the following:

class User
    has_many :teams, :foreign_key => "owner_id" #user owns this team
    has_many :memberships #user is a member of these teams


class Team
    belongs_to :team_administrator, :class_name => "User", :foreign_key => "owner_id"
    has_many :memberships

class Membership
    belongs_to :team
    belongs_to :user

I don't like the team administrator part, because I have to maintain that he's both in a membership and that he owns a team. Maybe it would be better to have an is_administrator property of Membership ?

Another problem with this model is that I'm struggling to find a nice way of determining if UserA is a member of a team that UserB owns. I'm currently doing:

Membership.first(:joins => :team, :conditions => {:id => params[:membership_id], :teams => {:owner_id => current_user}})

Where membership_id is the membership containing the user I'm trying to determine is a member of a team belonging to current_user.

So, anyone have a better way to model this?

Thanks for any advice!

Edit: A user can indeed be an owner/member of multiple teams

What you need is polymorphism:

class User
    has_many :teams, :as => team_administrator, :foreign_key => "owner_id"
    has_many :teams, :through => :memberships #user is a member of these teams
    has_many :memberships

class Team
    belongs_to :team_administrator, :polymorphic => true, :foreign_key => "owner_id"
    has_many :users, :though => memberships

class Membership
    belongs_to :team
    belongs_to :user

To find out whether a user A is part of B's team:

b = User.find_by_name("B")
a = User.find_by_name("A")
a.teams.find_by_owner_id(b.id)

用另一种方式找到会员

@membership = current_user.membership.find(params[:membership_id], :joins => :team)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM