ruby on rails 3-如何在组和用户之间创建联接操作



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

组.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

成员_控制器.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

用户通过成员关系模型(一个联接表(拥有组。我的问题。如何为用户创建可单击的加入操作,以便他们可以加入组?

您已经完成了添加控制器操作的步骤1。现在,您只需要添加适当的路线并将其连接到视图中即可。

在您的routes.rb:中

resources :groups do
    get 'join', :on => :member
end

在您的视图文件中:

<%= link_to "Join this group", join_group_path(@group) %>

就是这样!

相关内容

  • 没有找到相关文章

最新更新