如何在自联接表中创建has_many through关系?

时间:2013-12-24 03:51:08

标签: ruby-on-rails activerecord

我目前有自己加入的表,但是当我尝试创建多对多的更新时,它一次只能存储一个关系。我查看了ruby on rails指南中的has_many through关系,但它处理的是Employee Manager Subordinate案例,这与我的示例不同。你如何创建一个has_many:through与自联接表的关系?

Word模型

class Word < ActiveRecord::Base
  has_many :synonyms, :foreign_key => 'synonym_id', :class_name => 'Word'
end

我正在尝试做的例子

good = Word.create(name:'good')
pleasant = Word.create(name:'pleasant')
fine = Word.create(name:'fine')

good.synonyms << pleasant
good.synonyms << fine

pleasant.synonyms << good
pleasant.synonyms << fine

fine.synonyms << good
fine.synonyms << pleasant

good.synonyms # Empty - fine and pleasant should be resultset
pleasant.synonyms # Empty - good and fine should be in this resultset
fine.synonyms # Has the foreign keys to good and pleasant

Word Schema

create_table "words", force: true do |t|
  t.string   "name", null: false
  t.integer  "synonym_id"
end

谢谢你的帮助!

0 个答案:

没有答案