My has_many :through association of Users, Groups, and Memberships is causing trouble in some methods
I am working with a has_many :through association: Users join Groups through a Membership. I am having trouble with some methods I created in the user model to determine if the user is a member of a group, and to 开发者_运维知识库allow a user to join and leave a group. Using the console, memberships.find_by_group_id
always returns nil. I am not sure why and I think it might be the way I have set up my has_many :through associations, though after looking it over many, many times and consulting railscasts/blogs it seems ok. If you want me to post more info, like the schema.db or something, let me know
class User < ActiveRecord::Base
has_many :memberships, :dependent => :destroy
has_many :groups, :through => :memberships
.
.
.
def member?(group)
memberships.find_by_group_id(group)
end
def join!(group)
memberships.create!(:group_id => group.id)
end
def leave!(group)
memberships.find_by_group_id(group).destroy
end
.
.
.
end
class Group < ActiveRecord::Base
has_many :memberships
has_many :members, :through => :memberships, :source => :user
has_attached_file :photo, :styles => { :thumb => "100x100",
:small => "200x200" }
attr_accessible :name, :description, :private, :created_at, :group_id
attr_accessible :photo, :photo_file_name, :photo_content_type,
:photo_file_size, :photo_updated_at
end
class Membership < ActiveRecord::Base
attr_accessible :group_id
belongs_to :user
belongs_to :group
end
Here is the membership controller:
class MembershipsController < ApplicationController
def create
@group = Group.find(params[:membership][:group_id])
current_user.join!(@group)
respond_to do |format|
format.html { redirect_to @group }
format.js
end
end
def destroy
@group = Membership.find(params[:id]).group
current_user.leave!(@group)
respond_to do |format|
format.html { redirect_to @group }
format.js
end
end
def index
@memberships = Membership.all
end
end
I think what you are looking for is :has_and_belongs_to_many
(N-N) association rather than :has_many
(1-N) association.
It seems that each group can have many users as well.
Take a look at official rails guides at http://guides.rubyonrails.org/association_basics.html#has_and_belongs_to_many-association-reference
Using :has_and_belongs_to_many relationships, it will be really easy to add a collection(user) to the other collection(membership) .
For example
@membership.users << current_user
will add current_user to the membership
and
@membership.users.delete(current_user)
will delete current_user from the membership.
精彩评论