可能有人點我到正確的方向:軌多對多自聯接
我嘗試建立軌道是建立以下模型:
ClassA的 -id
ClassA的與許多「ClassA」有關係(所以它是對自身的引用)
我正在尋找遷移和模型。
我一個不知道正確的連接表(我認爲這是一個簡單的2列的表ClassA_id,ClassARel_ID - >都指向ClassA的),以及如何構建模型
謝謝!
可能有人點我到正確的方向:軌多對多自聯接
我嘗試建立軌道是建立以下模型:
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
謝謝,只是一個問題,以瞭解背景: 如何知道rails belongs_to:friend,:foreign_key =>「friend_id」,:class_name =>「Person」在友誼表(字段friend_id)中定義? – awex 2010-08-03 13:44:38
我不確定我是否理解你的問題。正如我們可以在railsapi.com上看到的那樣,「在大多數情況下,將給定的Active Record類綁定到特定數據庫表的映射將自動發生」。這裏就是這種情況,因爲類和表名。 – 2010-08-03 13:58:56
不知道爲什麼這不被接受。是一個非常好的答案。我需要嘗試一下,我會看看它是否按預期行事。 – Amala 2010-11-22 03:34:28
如果沒有什麼太大的意義創建另一個類參加這兩項,另一種方法可以是:
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
不幸的是惠斯勒答案在很多情況下可能不適用。例如,它不能同時工作。舉例來說,假設您創建了一個新詞:
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.
這在說'振動'一詞沒有同義詞。
所以基本上,這種方法是行不通的兩種方式(即振動是顫抖的代名詞,和顫抖是振動的同義詞)
編輯:在某種意義上,你可以使用這種方法,但是,你將不得不爲每個單詞明確分配同義詞。因此,儘管您指定了顫音的同義詞(它們是「震動」和「震動」),但您仍然必須指定「震動」('振動'和'振動')和'振動'顫抖'和搖')以及。
你能給我們一個具體的例子嗎?這就像一個擁有父母的人(顯然也是一個人)?或者你想像「Cars.all.green」一樣說要返回所有綠色汽車嗎? – 2010-08-03 13:22:10
是的,它就像人有很多朋友(人) – awex 2010-08-03 13:27:47