小编典典

棘手的活动记录关系-多态双向自引用

sql

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

出版物可以是文章,书籍或一章,并且具有对其他出版物的许多引用,并且其他出版物也引用了该出版物(称这些引用)

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

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

我的刺

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

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

我可能还需要使用很多方法,因为我需要破坏关系的能力


阅读 174

收藏
2021-04-15

共1个答案

小编典典

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

$ 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">]
2021-04-15