gpt4 book ai didi

sql - 棘手的事件记录关系——多态双向自引用

转载 作者:行者123 更新时间:2023-12-04 05:22:20 26 4
gpt4 key购买 nike

您将如何对出版物(文章、书籍、章节等)的引用文献和引文建模?

一个出版物可以是一篇文章、一本书或一个章节,它有很多对其他出版物的引用,其他出版物也引用了它(称为这些引用)

我需要能够列出出版物之间的关系:出版物中的引用文献以及其他出版物对该出版物的引用

我最初的理解是,这将是一种处理不同类型发布的多态关系,并且需要双向自连接。

我的刺

Publication
belongs_to :writing, :polymorphic =>true
has_and_belongs_to_many :references
:class_name => "Publication"
:join_table => 'reference_citation'
:foreign_key => 'reference_id'
:foreign_key => 'citation_id'

Book, Chapter, Article all have:
has_many :publications :as =>writing

我觉得这有点令人困惑,所以任何有助于澄清它的建议都会很棒。甚至对象和字段命名建议。

[我问了这个问题不太清楚的版本 here .]

我也可能需要使用 has many through 因为我将需要破坏关系的能力

最佳答案

这是使用单表继承的自引用关系的解决方案。使用这些命令来创建应用程序:

$ rails myproject
$ cd myproject
$ script/generate model publication type:string name:string
$ script/generate model citation publication_id:integer reference_id:integer

以这种方式设置关系:
class Publication < ActiveRecord::Base
has_many :citations
has_many :cited_publications, :through => :citations, :source => :reference
has_many :references, :foreign_key => "reference_id", :class_name => "Citation"
has_many :refered_publications, :through => :references, :source => :publication
end

class Citation < ActiveRecord::Base
belongs_to :publication
belongs_to :reference, :class_name => "Publication"
end

class Article < Publication
end

class Book < Publication
end

class Chapter < Publication
end

现在我们可以创建数据库并从控制台尝试它:
$ rake db:migrate
$ script/console
Loading development environment (Rails 2.2.2)
>> a = Article.create!(:name => "Article")
=> #<Article id: 1, ...>
>> b = Book.create!(:name => "Book")
=> #<Book id: 2, ...>
>> a.citations.create(:reference => b)
=> #<Citation id: 1, publication_id: 1, reference_id: 2, created_at: "2009-02-15 14:13:15", updated_at: "2009-02-15 14:13:15">
>> a.citations
=> [#<Citation id: 1, ...>]
>> a.references
=> []
>> b.citations
=> []
>> b.references
=> [#<Citation id: 1, publication_id: 1, reference_id: 2, created_at: "2009-02-15 14:13:15", updated_at: "2009-02-15 14:13:15">]
>> a.cited_publications
=> [#<Book id: 2, type: "Book", name: "Book", created_at: "2009-02-15 14:11:00", updated_at: "2009-02-15 14:11:00">]
>> a.refered_publications
=> []
>> b.cited_publications
=> []
>> b.refered_publications
=> [#<Article id: 1, type: "Article", name: "Article", created_at: "2009-02-15 14:10:51", updated_at: "2009-02-15 14:10:51">]

关于sql - 棘手的事件记录关系——多态双向自引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/536261/

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