如何管理多对多关系

时间:2012-09-18 17:19:52

标签: ruby-on-rails ruby-on-rails-3 activerecord

我有两个模型GroupPerson,我想要有多对多关系,但我不清楚如何管理关系本身。我希望能够分别创建组和人 - 不一定是通过嵌套模型 - 然后将人员从组视图/模型本身链接到组。

有没有人对如何这样做有任何建议?

我想通过连接模型创建多对多关系,然后在Group模型中接受连接模型的嵌套属性 - 所以我相信我将能够通过连接模型添加和删除关系Group视图/模型。这种方法有意义吗?

2 个答案:

答案 0 :(得分:1)

我会创建一个PersonGroup模型,如下所示:

class PersonGroup < ActiveRecord::Base
  has_many :people
  has_many :groups
end

您也可以执行rails generate migration create_person_group并将其放在生成的迁移文件的up方法中:

create_table :person_group do |t| 
  t.integer :person_id, :null => false
  t.integer :group_id, :null => false

  t.timestamps
end 

add_index :person_group, [:person_id, :group_id], :unique => true

然后在Person

class Person < ActiveRecord::Base
  has_many :person_groups
  has_many :groups, :through => :person_groups
end

Group

class Group < ActiveRecord::Base
  has_many :person_groups
  has_many :people, :through => :person_groups
end

答案 1 :(得分:0)

创建junction table。当您想要存储多对多关系时,使用连接表。我没有在ROR中开发,所以我不知道ActiveRecord的具体细节,但我相信这也可以帮助你思考这个问题。

group_id INTEGER,
person_id INTEGER
相关问题