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"}
You can add user to group by doing this in your controller:
For assigning group to user:
EDIT: As per your comment