views:

33

answers:

2

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 and an editor of another.

+1  A: 

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?

Jim Puls
has_and_belongs_to_many :authored_publications, :class_name => "Publication", :join_table => :authors_publications
Ermin
has_and_belongs_to_many :edited_publications, :class_name => "Publication", :join_table => :editors_publications
Ermin
A: 

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 
j.