Rails Many to Many Create Controller

fuller picture fuller · Jan 11, 2013 · Viewed 8k times · Source

and thanks in advance for any help offered here. I'm new to rails development and stackoverflow actually. I'm creating a many to many relationship and having trouble with some basics. I'm wanting to do a User and Groups relationship.

Models:

    class User < ActiveRecord::Base
      attr_accessible :name
      has_and_belongs_to_many :groups
    end

    class Group < ActiveRecord::Base
      attr_accessible :name
      has_and_belongs_to_many :users
    end

db/migrate create_groups_users_join

class CreateGroupsUsersJoin < ActiveRecord::Migration
  def self.up
    create_table 'groups_users', :id => false do |t|
      t.column 'group_id', :integer
      t.column 'user_id', :integer
     end
   end
 def self.down
   drop_table 'groups_users'
 end
end

I created a dropdown on my users form with this code.

true }) %>

controllers

def edit
  @user = User.find(params[:id])
  @groups = Group.all
  ...
end
  def new
  @user = User.new
  @groups = Group.all
  ...
end

I'm lost now as far as what to add to the controller to update the join table on creations/edits/updates. Can anyone explain what I need to change to make this happen? Thank you.

Here's the Error output I am getting now:

 {"utf8"=>"✓",
    "authenticity_token"=>"pgyajCT23qQVMuS+MQgG6E7M7Q8AWjfGaYbe3q7QDSA=",
    "group"=>{"group_id"=>"1"},
    "user"=>{"name"=>"ymudfg"},
    "commit"=>"Create User"}

Answer

Rahul Tapali picture Rahul Tapali · Jan 11, 2013

You can add user to group by doing this in your controller:

   user = User.find(params[:uid])
   group = Group.find(params[:gid])

   group.users <<  user  #Adding user to group

For assigning group to user:

   user.groups << group

EDIT: As per your comment

  class UsersController < ApplicationController
    def new
      @user = User.new
      @group = Group.all
    end

    def create
      @user = User.new(params[:user])
      @group = Group.find(params[:group][:group_id]) # As per log
      if @user.save
        @group.users << @user
      else
        render :new
      end
    end

    #Similarly you can implement edit
  end