您需要告诉 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
问题是您有两个表,将 id 放在一列中,Rails 不知道要查找哪个表。
例如,在数据库中任何给定的 connection_binding 行上,connect_from 可以是 company_id 或 person_id,connect_to 也是如此。所以你说:'Hey 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
您需要在另一端构建它(以及相关的 :from_connect),但这取决于您如何使用这些连接。应该足以让你开始。
它比您在 Ruby 和 Rails 的神奇世界中所习惯的要多得多,但您正在尝试构建一个非常复杂的数据模式。这并不意味着它是不可能的——Rails,作为一个好的框架,不会阻止你做任何你真正想做的事情——但它并不常见到需要一些明确的结果。