活动记录递归多对多关联

时间:2014-07-18 18:27:00

标签: sql ruby-on-rails activerecord recursion

我想与模型Projects

建立多对多递归关联

项目has_many比较(或可比较),其他项目

和项目可以是许多项目的比较

我想在每条记录中添加其他列,因此我需要一个连接表

我做了以下没有帮助的研究:

  1. This article is a clear basic explanation of sql recursive associations, but there is no specifics on activerecord implementation
  2. this stack overflow article deals with a one-to-many relationship, and not a many-to-many
  3. I tried this rails method of setting up what seems to be multiple join tables, but it is confusing and did not work for me.
  4. I tried this rails method and it did not work for me, maybe because it assigns primary keys to two columns in a table, which I did not do
  5. 在最后一个链接中,这是有问题的代码:

    CREATE TABLE tutorship ( tutor_id INTEGER, tutored_id INTEGER, hasPaid BOOLEAN, PRIMARY KEY (tutor_id, tutored_id) ); 如何在同一个表中有两个主键?如果这是正确的,这是问题,我该如何设置?

    一般来说,我如何在活动记录中设置它?

2 个答案:

答案 0 :(得分:3)

你正在寻找的术语似乎是“自我引用多对多”。 当你构建它时,第一次正确地建议测试并重新测试你在rails控制台中的关联是非常棘手的。

```

class Project < ActiveRecord::Base

  has_many :comparables
  has_many :comps, :through => :comparables

  # rest of class omitted. 
end

class Comparables < ActiveRecord::Base
  belongs_to :project
  belongs_to :comp, :class_name => 'Project'
end

```

如果我在上面的例子中犯了错误,有人会纠正我。

答案 1 :(得分:0)

您不能拥有多个主键。按照这个定义,这没有意义。但是,您可以拥有多个唯一索引。你所描述的不是递归的。这是一对多关系。我不太明白你真正想要的是什么,因为你有一些代码可以谈论导师,但你的原始评论必须与项目有关。

让我们说你有项目。任何给定的项目都可以有多个comps。同时,任何给定的comp都可以与多个项目相关联。你这样做的方法是使用联合表。

沿着这些方向发展。

create table Projects
(
    ProjectID int,
    OtherColumnsHere
)

create table Comps
(
    CompID int,
    OtherColumnsHere
)

create table ProjectComps
(
    ProjectID int,
    CompID int,
    AuditingColumnsLikeDateCreatedHere
)
相关问题