2010-05-20 43 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 
相关问题