【问题标题】:How do I do multiple has_and_belongs_to_many associations between the same two classes?如何在相同的两个类之间进行多个 has_and_belongs_to_many 关联?
【发布时间】:2010-05-20 17:33:28
【问题描述】:

我有以下设置:

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 的错误。我该如何解决?

我是否应该为作者和编辑切换到单独的模型?然而,它会给数据库带来一些冗余,因为一个人可以是一个出版物的作者和另一个出版物的编辑。

【问题讨论】:

    标签: ruby-on-rails has-and-belongs-to-many


    【解决方案1】:

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

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

    person.publications << Publication.new
    

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

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

    【讨论】:

    • has_and_belongs_to_many :authored_publications, :class_name => "Publication", :join_table => :authors_publications
    • has_and_belongs_to_many :edited_publications, :class_name => "Publication", :join_table => :editors_publications
    【解决方案2】:

    我相信你应该在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 
    

    【讨论】:

      猜你喜欢
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      相关资源
      最近更新 更多