has_many :memberships, :dependent => :destroy
has_many :groups, :through => :memberships
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
has_many :memberships, :dependent => :destroy
has_many :users, :through => :memberships
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
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
用户通过成员资格模型获得组,这是一个连接表。我的问题。如何创建联接操作以供用户单击以便他们可以加入组?
答案 0 :(得分:2)
您已完成步骤1,即添加控制器操作。现在,您只需添加适当的路线并在视图中将其连接起来。
在routes.rb
:
resources :groups do
get 'join', :on => :member
end
在您的视图文件中:
<%= link_to "Join this group", join_group_path(@group) %>
就是这样!