Rails使用foreign_key和链接表进行建模 [英] Rails model with foreign_key and link table
问题描述
我正在尝试创建一个Ruby on Rails项目的模型,以建立不同单词之间的关系。把它看作是一个字典,其中两个单词之间的链接表明它们可以同义使用。我的数据库看起来像这样:
I am trying to create a model for a ruby on rails project that builds relationships between different words. Think of it as a dictionary where the "Links" between two words shows that they can be used synonymously. My DB looks something like this:
Words
----
id
Links
-----
id
word1_id
word2_id
如何使用链接表创建两个单词之间的关系。我试图创建模型,但不知道如何获得链接表:
How do I create a relationship between two words, using the link-table. I've tried to create the model but was not sure how to get the link-table into play:
class Word < ActiveRecord::Base
has_many :synonyms, :class_name => 'Word', :foreign_key => 'word1_id'
end
推荐答案
如果您的关联有后缀(如1和2),则设置不正确。试试这个Word模型:
In general, if your association has suffixes such as 1 and 2, it's not set up properly. Try this for the Word model:
class Word < ActiveRecord::Base
has_many :links, :dependent => :destroy
has_many :synonyms, :through => :links
end
链接模式:
Link model:
class Link < ActiveRecord::Base
belongs_to :word
belongs_to :synonym, :class_name => 'Word'
# Creates the complementary link automatically - this means all synonymous
# relationships are represented in @word.synonyms
def after_save_on_create
if find_complement.nil?
Link.new(:word => synonym, :synonym => word).save
end
end
# Deletes the complementary link automatically.
def after_destroy
if complement = find_complement
complement.destroy
end
end
protected
def find_complement
Link.find(:first, :conditions =>
["word_id = ? and synonym_id = ?", synonym.id, word.id])
end
end
表:
Tables:
Words
----
id
Links
-----
id
word_id
synonym_id
这篇关于Rails使用foreign_key和链接表进行建模的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!