2012-09-08 25 views
1

我在編寫組織科學論文的Rails應用程序時遇到了一些麻煩。如何在Rails 3中構建自我參照關聯?

每個紙具有許多參考文獻(其他文件) - >甲論文引用許多論文 每個紙具有許多引用(其他文件中,逆關係) - >的紙是由許多論文

我的目的引就是爲了能夠訪問這樣

@paper = Paper.first 
@paper.references => [Papers that @paper is citing] 
@paper.citations => [Papers that @paper is being cited by] 

這裏,論文的引用和引文是我採取的步驟:

# console 
rails g model paper title # Generate Paper model 
rails g model citation paper_id:integer reference_id:integer # Generate Citation Model 

# app/models/paper.rb 
class Paper < ActiveRecord::Base 
    # Relations 
    has_many :reference_relations, class_name: 'Citation' 
    has_many :citation_relations, class_name: 'Citation', foreign_key: 'reference_id' 

    # References and citations 
    has_many :references, through: :reference_relations 
    has_many :citations, through: :citation_relations, source: :paper 

    attr_accessible :title 
end 

# app/models/citation.rb 
class Citation < ActiveRecord::Base 
    belongs_to :paper       # Source of the reference, paper that is citing 
    belongs_to :reference, class_name: 'Paper' # Paper that is being referenced and cited 

    # attr_accessible :reference_id # This should not be accessible, should it? 
end 

無W I嘗試建立一個參考:

p = Paper.first 
r = Paper.last 
p.references.build(reference_id: r.id) 

當我嘗試但是建立一個引文,我得到一個ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: reference_id錯誤。我首先假定Citation模型中的attr_accessible可能需要設置,但事實證明,ActiveRecord試圖將reference_id分配給紙張實例而不是新的引用實例。

將兩張紙連接起來的最佳方式是什麼?如何構建這些連接?

感謝您的幫助提前!

+0

請添加您的參考模型代碼。 –

+0

我沒有具體的參考模型。我認爲一篇參考文獻是另一篇論文參考文獻中列出的論文,並且引用是相反的。 –

+0

@MichaelDurrant我添加了一些關於我想要實現的內容並對代碼進行編輯的說明。感謝您的幫助! –

回答

1

我不認爲它是自引用的,因爲連接是通過引用,而不是直接在紙上。

所以我將接近這樣的:

Paper 
has_many :citation_papers 
has_many :citations, :through => citation_papers 

Citation 
has_many :citation_papers 
has_many :papers, :through citation_papers 

CitationPaper # Needs the two ID's 
belongs_to :paper 
belongs_to :citation