铁路多对多自我加入
有人可以指出我正确的方向:
我尝试为构建以下内容的rails构建模型:
ClassA -id
ClassA与许多“ClassA”有关系(因此它是对自身的引用)
我正在寻找迁移和模型。
我不确定正确的连接表是什么(我认为它是一个简单的2列表ClassA_id,ClassARel_ID – >都指向ClassA)以及如何构建模型
谢谢!
我会用类似的东西
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
如果创建另一个类加入这两个类没有多大意义,另一种方法可能是:
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
这篇文章有一个很好的工作示例: http : //blog.hasmanythrough.com/2007/10/30/self-referential-has-many-through
这里也有一个相关的问题: 自引用的问题has_many:通过Rails中的关联
不幸的是,惠斯勒的答案在许多情况下可能并不合适。 例如,它不是双向的。 例如,假设您创建了一个新单词:
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.
这就是说’vibrate’这个词没有同义词。
所以基本上,这种方法不会兼顾两种方式(即振动是颤抖的同义词,颤抖是振动的同义词)
编辑:从某种意义上说,您可以使用此方法,但是,您必须为每个单词显式分配同义词。 因此,尽管你指定了颤抖的同义词(’vibrate’和’shake’),你仍然必须指定’shake’(”颤抖’和’振动’)和’振动’的同义词(它们是’同样颤抖’摇晃’)。