Rails 自我参照 has_many 联想

Rails self-referential has_many association

在 Rails 上使用 Ruby,我想我需要创建一个自引用 has_many 关联来模拟中文单词。

背景:

每个单词都是多个 component 单词的 composite

例如,如果我有三个词,'ni'、'hao'和'nihao',我希望能够做到:

nihao.components = ['ni', 'hao']

'ni'.composites = ['nihao']
'hao'.composites =['nihao']

我不认为这应该是一个层次关联(我见过几个宝石...)因为一个词没有 1 或 2 "parents",它有 0、1 或数百 "composites"。同样,一个单词有 0 个、1 个或多个 "components".

我试过:

class Word < ActiveRecord::Base
  has_many :relationships
  has_many :components, through: :relationships, foreign_key: :component_id
  has_many :composites, through: :relationships, foreign_key: :composite_id
end

class Relationship < ActiveRecord::Base
  belongs_to :component, class_name: "Word"
  belongs_to :composite, class_name: "Word"
end

这不太正确,因为我无法添加组件:

nihao.components << ni
   (0.2ms)  BEGIN
   (0.2ms)  ROLLBACK
ActiveModel::UnknownAttributeError: unknown attribute 'word_id' for Relationship.
        from (irb):5

数据库架构:

create_table "relationships", force: :cascade do |t|
    t.integer "component_id"
    t.integer "composite_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "words", force: :cascade do |t|
    t.string "characters"
    t.string "pinyin"
    t.string "opinyin"
    t.string "tpinyin"
    t.string "english"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

试试这个,你没有为这种用例正确关联你的模型。

class Word < ActiveRecord::Base
  has_many :component_relationships, class_name: 'Relationship', foreign_key: :composite_id
  has_many :composite_relationships, class_name: 'Relationship', foreign_key: :component_id

  has_many :components, through: :component_relationships
  has_many :composites, through: :composite_relationships
end 

class Relationship < ActiveRecord::Base
  belongs_to :component, class_name: "Word", foreign_key: :component_id
  belongs_to :composite, class_name: "Word", foreign_key: :composite_id
end

我还没有尝试过,但这应该可以。