开发者

How do I do multiple has_and_belongs_to_many associations between the same two classes?

I have the following setup:

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

With this setup I can do stuff like Publication.first.authors. But if I want to list all publications in which a person is involved Person.first.publications, an error about a missing join table people_publications it thrown. How could I fix that?

Should I maybe switch to separate models for authors and editors? It would however introduce some redundancy to the database, since a person can be an author of one publication开发者_C百科 and an editor of another.


The other end of your associations should probably be called something like authored_publications and edited_publications with an extra read-only publications accessor that returns the union of the two.

Otherwise, you'll run in to sticky situations if you try to do stuff like

person.publications << Publication.new

because you'll never know whether the person was an author or an editor. Not that this couldn't be solved differently by slightly changing your object model.

There's also hacks you can do in ActiveRecord to change the SQL queries or change the behavior of the association, but maybe just keep it simple?


I believe you should have another association on person model

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 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜