0

我正在构建一个应用程序,用户可以在其中创建一个组,然后邀请其他用户加入他的组。一个用户可以加入许多组,一个组将包含许多用户。我对如何将指定用户添加到指定组感到困惑。例如,我有一个 ID 为 2 的用户对象。如何获取此用户对象并将其添加到指定组?我可以使用 User.first.groups.create 创建一个组,但我无法反其道而行之。

例如,我尝试: Group.first.create(user_id: 1) 将用户 1 添加到组 1。Rails 不喜欢这样。

我有以下数据库设计:

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

我还使用以下迁移创建了一个连接表:

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

提前感谢您的所有帮助!

4

1 回答 1

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

group是您要添加到的特定组(在您的快速示例中,它是Group.first.

于 2013-03-17T02:18:08.230 回答