探している関連付けられた列を 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 を 1 つの列に入れる 2 つのテーブルがあり、Rails がどのテーブルを検索すればよいか分からないことです。
たとえば、データベース内の特定の connection_binding 行では、connect_from は company_id または person_id のいずれかであり、connect_to についても同じことが当てはまります。だからあなたはこう言います:「ヘイ、Rails、私の関連付けられた ConnectionBindings を読み込んでください」と、connect_from が 11 で connect_to が 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 は、あなたが本当にやりたいことを止めることはありません – しかし、それはあまり一般的ではなく、あなたの側でいくらか明示する必要があります.