Ruby on rails Rails自引用有很多关联
使用RubyonRails,我想我需要创建一个自我引用,它与中文中的单词模型有很多关联 背景: 每个单词都是由多个成分组成的复合词 例如,如果我有三个词‘ni’、‘hao’和‘nihao’,我希望能够做到:Ruby on rails Rails自引用有很多关联,ruby-on-rails,associations,has-many,self-reference,Ruby On Rails,Associations,Has Many,Self Reference,使用RubyonRails,我想我需要创建一个自我引用,它与中文中的单词模型有很多关联 背景: 每个单词都是由多个成分组成的复合词 例如,如果我有三个词‘ni’、‘hao’和‘nihao’,我希望能够做到: nihao.components=['ni','hao'] 和 'ni'.composites=['nihao'] 'hao'.composites=['nihao'] 我不认为这应该是一个等级关联(我见过几个宝石…),因为一个单词没有1或2个“父”,它有0、1或数百个“复合”。同样,一个单
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
试试这个,你没有为这种用例正确地关联你的模型
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
classword
我没有试过这个,但这个应该有用 您可以添加这两个模型的模式吗@DanielThanks@AakashGupta,我在原始问题中添加了模式(不知道如何在注释中添加代码块!),谢谢!工作完美。
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