Create 'groups' that users can join, what would be a good approach?
I want to build "groups" that users can join, The flow of steps and things needed is in my head but the code to build thi开发者_StackOverflow社区s lacks some bit since I'm still learning rails. I would like to ask some advice on your ideas best practice of what would be needed to accomplish below:
- You can create a group with a name 'test'
- You automatically join the group test, other users can join to
- If want to see a list of the users joined my group 'test'
Im thinking of creating a model sessions like groups|name| But then how could I store the multiple users that are in this session? Should I make an array of the user_id's for example and make an extra column like groups|name|user_ids ?
What would be best practice and what rails (3) methods could I use to get a very rough version of the above functionality up and running ?
From what I understand this is a many to many relationship. So you would have 3 models :
class User < AR
has_many :memberships
has_many :groups, :through => :memberships
end
class Membership < AR
belongs_to :user
belongs_to :group
end
class Group < AR
has_many :memberships
has_many :users, :through => :memberships
end
and to know what users belong to a group :
@group = Group.find_by_name("test")
@users_group = @group.users
Update
to ensure the user creating the group also belongs to it :
# in group_controller.rb
def create
@group = Group.new(params[:group])
@group.users << current_user
if @group.save
# ... etc
end
end
of course the current_user
should exist/be logged in with the usual before_filter
(if I remember correctly its authenticate!
with devise)
Sorry i'm creating a new thread, but I am unable to comment as of my new status right now.
@charlysisto your answer for this question involves a User, Membership, and Group class. I understand the need of User and Group, but I am confused to why we would need a Membership class. If anything doesn't it make more sense to have a Groups class with Group?
class User < AR
belongs_to :group
belongs_to :groups, :through => :group
end
class Groups < AR
has_many :groups
has_many :users, :through => :group
end
class Group < AR
has_many :users
belongs_to :groups
end
What do you think?
精彩评论