双多态关联

Run*_*For 1 ruby-on-rails has-many-through polymorphic-associations

在我的rails应用程序中,我有两个模型: PersonCompany.我需要在这些对象的任何对之间指定多对多关系.所以我应该能够这样做:

@connections = @person.connections
Run Code Online (Sandbox Code Playgroud)

其中@connections是一个PersonCompany对象的数组.

现在我已经ConnectionBinding为此创建了模型,它不能按原样运行:

class ConnectionBinding < ActiveRecord::Base
  belongs_to :connect_from, polymorphic: true
  belongs_to :connect_to,   polymorphic: true
end
Run Code Online (Sandbox Code Playgroud)

这是个ActiveRecord::HasManyThroughAssociationPolymorphicSourceError例外

有人已经解决了这个问题吗?任何建议赞赏.

Chr*_*ris 5

您需要告诉ActiveRecord它正在寻找的关联列.我猜你想拥有以下内容:

class Person < ActiveRecord::Base
  has_many :connection_bindings
  has_many :companies, :through => :connection_bindings
  has_many :people, :through => :connection_bindings
end

class company < ActiveRecord::Base
  has_many :connection_bindings
  has_many :companies, :through => :connection_bindings
  has_many :people, :through => :connection_bindings
end
Run Code Online (Sandbox Code Playgroud)

问题在于你有两个表将id放在一列中,而Rails不知道要查找哪个表.

例如,在数据库中任何给定的connection_binding行上,connect_from可以是company_id或person_id,connect_to也是如此.所以你说:'嘿Rails,加载我关联的ConnectionBindings',它得到一行,其中connect_from是11,connect_to是12.但是它是Person.find(12)还是Company.find(12)?没有办法说出来!

相反,您必须为Rails提供更多信息:

class Person < ActiveRecord::Base
  has_many :connection_bindings
  has_many :person_connections, :through => :connection_bindings, :source => :to_connect, :source_type => 'Person'
  has_many :company_connections, :through => :connection_bindings, :source => :to_connect, :source_type => 'Company

  def connections
    person_connections + company_connections
  end
end
Run Code Online (Sandbox Code Playgroud)

你需要在另一端构建它(以及相关的:from_connect),但这取决于你如何使用这些连接.应该足以让你入门.

它比你在Ruby和Rails的神奇世界中习惯的打字要多得多,但它是一个非常复杂的数据模式,你正在尝试构建它.这并不意味着它是不可能的 - 作为一个好的框架,Rails不会阻止你做任何你真正想做的事情 - 但是在你的目的上需要一些明确性是不常见的.