user.rb
has_many :memberships, :dependent => :destroy
has_many :groups, :through => :memberships
membership.rb
class Membership < ActiveRecord::Base
attr_accessible :user_id, :group_id
belongs_to :user
belongs_to :group
validates_uniqueness_of :user_id, :message => "You can only join one group!"
end
group.rb
has_many :memberships, :dependent => :destroy
has_many :users, :through => :memberships
groups_controller.rb
def join
@group = Group.find(params[:id])
@m = @group.memberships.build(:user_id => current_user.id)
respond_to do |format|
if @m.save
format.html { redirect_to(@group, :notice => 'You have joined this group.') }
format.xml { head :ok }
else
format.html { redirect_to(@group, :notice => 'Join error.') }
format.xml { render :xml => @group.errors, :status => :unprocessable_entity }
end
end
end
memberships_controller.rb
class MembershipsController < ApplicationController
before_filter :authenticate_user!
def create
@membership = current_user.memberships.build(:group_id => params[:group_id])
if @membership.save
flash[:notice] = "You have joined this group."
redirect_to :back
else
flash[:error] = "Unable to join."
redirect_to :back
end
end
def destroy
@membership = current_user.memberships.find(params[:id])
@membership.destroy
flash[:notice] = "Removed membership."
redirect_to :back
end
end
Users have groups through a membership model which is a join table. My question. How do I create a join action for users to click on so that they can join a group?