4

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.

4

2 回答 2

3

您的关联的另一端可能应该被称为类似的东西,authored_publicationsedited_publications带有一个额外的只读publications访问器,该访问器返回两者的联合。

否则,如果你尝试做类似的事情,你会遇到棘手的情况

person.publications << Publication.new

因为你永远不会知道这个人是作者还是编辑。并不是说这不能通过稍微改变你的对象模型来解决。

您还可以在 ActiveRecord 中执行一些技巧来更改 SQL 查询或更改关联的行为,但也许只是保持简单?

于 2010-05-20T17:41:19.383 回答
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 
于 2010-05-20T23:43:31.383 回答