你需要告诉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也是如此。所以你说:'嘿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作为一个好的框架不会阻止你做任何你真正想做的事情 - 但是为了达到你的目的,需要一些明确性是不常见的。
感谢名单指着我出去。你的回答非常有帮助。我在下一个答案中为我写下了实际的解决方案。 – RunFor 2013-03-13 01:04:57