Search code examples
ruby-on-rails-3database-designassociationsmodel-associationshas-and-belongs-to-many

Having a hard time with has_and_belongs_to_many associations. Not sure how to add objects to a specified instance of its "belongs_to" table


I'm building an app where a User can create a Group and then invite other Users to join his group. A User can join many Groups and a Group will include many Users. I'm confused as to how I can add a specified user to a specified group. For example I have a User object who's id is 2. How do I take this User object and add it to a specified group? I'm able to create a group with User.first.groups.create but I'm unable to do the reverse.

For example I tried: Group.first.create(user_id: 1) to add User 1 to Group 1. Rails didn't like that.

I have the following database design:

class User < ActiveRecord::Base
  attr_accessible :name, :provider, :uid
  has_and_belongs_to_many :groups
end

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

I also created a join table with the following migration:

class GroupsUsers < ActiveRecord::Migration
  def up
    create_table :groups_users, :id => false do |t|
      t.integer :group_id
      t.integer :user_id
    end
  end

  def down
    drop_table :groups_users
  end
end

Thanks in advance for all your help!


Solution

  • user = User.find(2) # this is user object you say you have already
    group.users << user
    group.save
    

    group is the specific group you are adding to (in your quick example, it'd be Group.first.