导致很多人自我加入

时间:2010-08-03 13:19:54

标签: ruby-on-rails

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

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

ClassA的    -id

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

我正在搜索迁移和模型。

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

谢谢!

4 个答案:

答案 0 :(得分:30)

我会使用像

这样的东西
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

表格就像

people: id; name; whatever-you-need    
friendships: id; person_id; friend_id

答案 1 :(得分:15)

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

class Word < ActiveRecord::Base 
  has_and_belongs_to_many :synonyms, class_name: "Word", 
                                     join_table: "word_synonyms",
                                     association_foreign_key: "synonym_id"
end

联接表如下所示:

create_table :word_synonyms do |t|
  t.integer :word_id
  t.integer :synonym_id
end

答案 2 :(得分:1)

答案 3 :(得分:0)

不幸的是,惠斯勒的答案在许多情况下可能并不合适。例如,它不是双向工作。例如,假设您创建了一个新单词:

word = Word.create(:word_name => 'tremble')
['shake', 'vibrate'].each { |syn| word.synonyms.create(:word_name => syn) }

现在,如果你这样做:

word = Word.find_by_word_name('tremble')
p word.synonyms # this would print out the Words with the word_name 'shake' and 'vibrate'.

然而, 如果你反过来这样做了:

word = Word.find_by_word_name('vibrate')

p word.synonyms # this would print an empty association.

这就是说&#39; vibrate&#39;没有同义词。

所以基本上,这种方法不会双向工作(即振动是颤抖的同义词,颤抖是振动的同义词)

编辑:从某种意义上说,您可以使用这种方法,但是,您必须为每个单词明确指定同义词。因此,虽然你指定了颤抖的同义词(振动&#39;振动&#39;震动&#39;),你仍然必须指定&#39; shake&#39;的同义词。 (&#39;颤抖&#39;振动&#39;)&#39;振动&#39; (也是'颤抖&#39;并且摇晃')。