2010-05-20 44 views
4

我有以下設置:如何在相同的兩個類之間執行多個has_and_belongs_to_many關聯?

class Publication < ActiveRecord::Base 
    has_and_belongs_to_many :authors, :class_name=>'Person', :join_table => 'authors_publications' 
    has_and_belongs_to_many :editors, :class_name=>'Person', :join_table => 'editors_publications' 
end 

class Person < ActiveRecord::Base 
    has_and_belongs_to_many :publications 
end 

有了這個設置,我可以做的東西一樣Publication.first.authors。但是,如果我想列出涉及某人的所有出版物Person.first.publications,則會拋出關於丟失的連接表people_publications的錯誤。我怎麼能解決這個問題?

我是否應該改用作者和編輯的獨立模型?然而,它會給數據庫帶來一些冗餘,因爲一個人可以是一個出版物的作者和另一個出版物的編輯。

回答

3

您的關聯的另一端可能應該被稱爲authored_publicationsedited_publications之類的東西,並帶有一個額外的只讀publications訪問器,該訪問器返回兩者的聯合。

否則,如果你試圖做的東西一樣

person.publications << Publication.new 

,因爲你永遠不知道的人是否是作者或編輯,你會運行到棘手的情況。這並不是說通過稍微改變對象模型就可以解決這個問題。

還有一些你可以在ActiveRecord中做的改變SQL查詢或改變關聯行爲的黑客,但也許只是保持簡單?

+1

has_and_belongs_to_many另一個關聯:authored_publications,:CLASS_NAME => 「出版」,:join_table =>:authors_publications – 2010-05-21 13:05:05

+0

has_and_belongs_to_many:edited_publications,:CLASS_NAME => 「出版」 ,:join_table =>:editors_publications – 2010-05-21 13:06:19

0

我相信你應該有person模型

class Person < ActiveRecord::Base 
    # I'm assuming you're using this names for your foreign keys 
    has_and_belongs_to_many :author_publications, :foreign_key => :author_id 
    has_and_belongs_to_many :editor_publications, :foreign_key => :editor_id 
end 
相關問題