导致很多人自我加入

awe*_*wex 16 ruby-on-rails

有人可以指出我正确的方向:

我尝试为构建以下内容的rails构建模型:

ClassA -id

ClassA与许多"ClassA"有关系(因此它是对自身的引用)

我正在寻找迁移和模型.

我不确定正确的连接表是什么(我认为它是一个简单的2列表ClassA_id,ClassARel_ID - >都指向ClassA)以及如何构建模型

谢谢!

Ju *_*ira 33

我会用类似的东西

class Person < ActiveRecord::Base
   has_many :friendships, :foreign_key => "person_id", 
      :class_name => "Friendship"

   has_many :friends, :through => :friendships
end

class Friendship < ActiveRecord::Base
   belongs_to :person, :foreign_key => "person_id", :class_name => "Person"
   belongs_to :friend, :foreign_key => "friend_id", :class_name => "Person"  
end
Run Code Online (Sandbox Code Playgroud)

表格就像

people: id; name; whatever-you-need    
friendships: id; person_id; friend_id
Run Code Online (Sandbox Code Playgroud)

  • 不知道为什么不被接受.是一个非常好的答案.我需要尝试这个,我会看看它是否符合预期. (3认同)

Ibr*_*mad 15

如果创建另一个类加入这两个类没有多大意义,另一种方法可能是:

class Word < ActiveRecord::Base 
  has_and_belongs_to_many :synonyms, class_name: "Word", 
                                     join_table: "word_synonyms",
                                     association_foreign_key: "synonym_id"
end
Run Code Online (Sandbox Code Playgroud)

连接表如下所示:

create_table :word_synonyms do |t|
  t.integer :word_id
  t.integer :synonym_id
end
Run Code Online (Sandbox Code Playgroud)