Hi,
I found a small ‘problem’ to which I think I found a solution.
But the solution feels a bit hacky.
I would like some feedback on it.
Say I have Groups & Users.
A group has many users, but a user can also belong to many groups.
Also, the role a user has in a group should be known.
- class Group < ActiveRecord::Base
- has_many :memberships
- has_many :users, :through => :memberships
- end
- class User < ActiveRecord::Base
- has_many :memberships
- has_many :groups, :through => :memberships
- end
- class Membership < ActiveRecord::Base
- belongs_to :group
- belongs_to :user
- validates_uniqueness_of :user_id, :scope => :group_id
-
this model has a field “role” which describes the role a
user has in the group
17. end
Now, this suffices for the database and the model, but in my routes
file I don’t want to expose memberships as resources (since they are
kind of artificial), so:
- map.resources :groups do |group|
-
group.resources :users
- end
- map.resources :users do |user|
-
user.resources :groups
- end
This works, I can now see which users are in a group(on /groups/2/
users), but there is no way to see what role they have.
My solution would be to give users a virtual attribute (role) which
should get filled in when they are acquired by a group.
something along the lines of
- class Group < ActiveRecord::Base
- has_many :memberships
- has_many :users, :through => :memberships
- def users_with_roles
-
array = []
-
memberships.each do |membership|
-
user = membership.user
-
user.role = membership.role
-
array << user
-
end
-
array
- end
- end
Now, I can use @group.users_with_roles in my userscontroller’s index
action and display the list of users, including their role in this
group.
Of course this needs some changes for finding single users also, and
code to handle saving in case of adding users to a group.
But before I go that way I need to be assured this is the/a way to go.
Like I said, it feels very hacky, so I guess there should be a better
way to do this.
Any thoughts on this subject?
Like I said, I don’t want to expose memberships to the outside world,
just users & groups.
Thanks, Mathijs