views:

271

answers:

1

Hello everyone

I have question regarding associations in Ruby on Rails. In the application there are projects, users, roles and groups. The project belongs to a group with users, a user can belong to many different groups but can only have one specific role within that group. For example:

In one group the user is the project owner, but in another group he is a writer.

What is the best way to implement this using the built in functions in Rails?

Thanks

+5  A: 

Here is a very quick set of models that should fulfill your requirements:

class User < ActiveRecord::Base
  has_many :group_memberships
  has_many :groups, :through => :group_memberships
end

class GroupMembership < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
  belongs_to :group
end

class Role < ActiveRecord::Base
  has_many :group_memberships
end

class Group < ActiveRecord::Base
  has_many :group_memberships
  has_many :users, :through > :group_memberships
end

Basically there is a join table that has a user, group and role id in it. I'll leave the migrations as an exercise for the questioner

efalcao