Reputation: 169
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
Upvotes: 1
Views: 236
Reputation: 12426
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)
Upvotes: 4
Reputation: 3043
find the membership the other way
@membership = current_user.membership.find(params[:membership_id], :joins => :team)
Upvotes: 1