gpt4 book ai didi

ruby-on-rails - 自引用 has_many 通过 Rails

转载 作者:行者123 更新时间:2023-12-04 07:38:37 24 4
gpt4 key购买 nike

我已经阅读了很多关于 Rails 中的自引用类的内容,但在使用它们时仍然遇到问题。

我有一个文章类,我希望它们能够相互引用,从源文章到结果文章 - 然后能够找到相反的文章。所以我尝试使用另一个名为 Links 的类来完成 has_many。

我的模式是

  create_table "articles", :force => true do |t|
t.string "name"
t.text "body"
t.datetime "created_at"
t.datetime "updated_at"
end

create_table "links", :force => true do |t|
t.integer "source_id"
t.integer "outcome_id"
t.string "question"
t.datetime "created_at"
t.datetime "updated_at"
end

模型是

class Article < ActiveRecord::Base
has_many :links_as_source, :foreign_key => "source_id", :class_name => "Link"
has_many :sources, :through => :links_as_source

has_many :links_as_outcome, :foreign_key => "outcome_id", :class_name => "Link"
has_many :outcomes, :through => :links_as_outcome
end

class Link < ActiveRecord::Base
belongs_to :source, :foreign_key => "source_id", :class_name => "Article"
belongs_to :outcome, :foreign_key => "outcome_id", :class_name => "Article"
end

我可以在控制台中创建文章,并且可以使用 a.outcomes << b 将文章链接在一起但链接表只存储 outcome_id,不存储 source_id。

我做错了什么?

最佳答案

我最终成功了。我改了名字——我不知道这是否重要。我确实在某处读到过 source 是一个愚蠢的名字。

所以这是有效的:

我的架构

create_table "article_relationships", :force => true do |t|
t.integer "parent_id"
t.integer "child_id"
...
end

create_table "articles", :force => true do |t|
t.string "name"
...
end

我的文章模型

has_many    :parent_child_relationships,
:class_name => "ArticleRelationship",
:foreign_key => :child_id,
:dependent => :destroy
has_many :parents,
:through => :parent_child_relationships,
:source => :parent

has_many :child_parent_relationships,
:class_name => "ArticleRelationship",
:foreign_key => :parent_id,
:dependent => :destroy
has_many :children,
:through => :child_parent_relationships,
:source => :child

关于ruby-on-rails - 自引用 has_many 通过 Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8136231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com