轨道自引用has_many关联



使用 Ruby on Rails,我认为我需要创建一个自我引用的has_many关联来模拟中文单词。

背景:

每个单词都是多个组成单词的组合。

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


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

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

我不认为这应该是一个等级关联(我见过几个宝石......(,因为一个单词没有 1 或 2 个"父母",它有 0、1 或数百个"复合"。同样,一个单词有 0、1 或几个"组件"。

我试过:

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

我没有尝试过这个,但这应该有效。

相关内容

  • 没有找到相关文章

最新更新